Week 7: Java Client and Server Using Sockets
Overview
- URLs and URLConnections are relatively high level in Java
networking
- Good for accessing resources on the Internet
- For client-server application, we need something in a
lower level - Socket
- Socket is "invented" by people from UCB
- In a client-server model, server provides some service,
such as processing database queries or sending out
current stock prices
- Client will send request to the server for services
- Services must be reliable - use TCP
What is a Socket
- Server listens to a specific port waiting for connection
requests from clients
- When trying to conect, the client is assigned a local
port number, and binds a socket to it
- The client talks to the server by writing to the socket
and gets information from the server by reading from it.
- The server also binds a socket to its local port and
communicates with the client by reading from and writing
to it.
- Definition: A socket is one end-point of a two-way
communication link between two programs running on the
network.
- Think about using the internet as calling the server,
socket will then be your phone
- Java provides Socket and ServerSocket classes in java.net
for doing client-server application
Read and Write Using Java Socket (Client Side)
- Socket is a platform-independent implementation for
two-way communication
- The Socket class sits on top of a platform-dependent
implementation
- Sockets hide the details of any particular system from
your Java program
- Client Programs usually follow the following steps
- Open a socket.
- Open an input stream and output stream to the socket.
- Read from and write to the stream according to the
server's protocol.
- Close streams.
- Close sockets.
Client Programming in Java
- Socket is just like URL class, we have to use try-catch
code to look for exception
- Socket will flow UnknownHostException
- Socket is usually used with DataInputStream and
DataOutputStream for reading and writing
- "Stream" will flow IOException to the Java
program
- Example:
try
{
echoSocket = new Socket("richard.rchland.ibm.com", 7);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
} catch (UnknownHostException e)
{
System.err.println("Don't know about host: richard.rchland.ibm.com");
} catch (IOException e)
{
System.err.println("Couldn't get I/O for the connection to: richard.rchland.ibm.com");
}
- Reading from a Java Socket
- Reads from standard input stream (where the user
can type data) a line at a time.
- Immediately writes the input text followed by a
newline character to the output stream connected
to the socket.
String userInput;
while ((userInput = stdIn.readLine()) != null)
{
os.writeBytes(userInput);
os.writeByte('\n');
System.out.println("echo: " + is.readLine());
}
//The readLine() method blocks until the server echos the information back
- Closing socket and stream
os.close();
is.close();
echoSocket.close();
Server Programming in Java
- Server is listening in a certain TCP port for incoming
request
(Java use a ServerSocket to do the listening)
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(8888);
} catch (IOException e) {
System.out.println("Could not listen on port: " + 8888 + ", " + e);
System.exit(1);
}
- When a request come in, it will accept
it
- The return of the accept method is a Socket (another
phone !) - the reason is that the server then can go back
and listen on the same port
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + 8888 + ", " + e);
System.exit(1);
}
- The server can, for example, read in the input of the
client and then echo back out to the same socket
// Standard Java way of doing input and output
BufferedReader is = new BufferedReader(new InputStreamReader( clientSocket.getInputStream() ));
PrintWriter os = new PrintWriter(new BufferedOutputStream(clientSocket.getOutputStream(), 1024), false);
String inputLine;
while ((inputLine = is.readLine()) != null) {
// Echo the line out
if (inputLine.equals("QUIT"))
break;
System.out.println("Input [" + inputLine + "] come in");
os.println(inputLine);
os.flush();
}
Lab
Create two Java applications EchoClient
and EchoServer to build a mini
client-server application that will enable the server to echo out
whatever the client input
The EchoClient application should
- Create a Socket to the local host (by looking at the
identification of Win95 network) and port 8888
- Ask the user for input
- Write all the input to the server using Socket
- If the input is "QUIT", close all the socket
and streams and quit the program
The EchoServer application should
- Create a ServerSocket on port 8888
- Accept the input request from a client
- Echo the client input back to the client using Socket
- If the input is "QUIT", close all the steam and
sockets, then exit the program
Note: The client and server programs should run in the same
machine (host). The server program should be started first.
Copyright
1996-2001 OpenLoop Computing. All rights reserved.