CS351 Spring 2004 Lab 13

Some Networking


Basic Networking Concepts

  • TCP vs UDP
  • Socket
  • Port, Address, and DNS
  • Loopback

Java Networking

In Java, we have a class Socket that provides the basic socket concept to us. To use it from the client side, we simply instantiate it:
	Socket s = new Socket("hostname", port)
Specifying a hostname as a string and the port as an integer. Note that if you give null for the hostname:
	Socket s= new Socket((String)null, port);
We get a socket on the loopback address.

From the server side, we use a ServerSocket.

	ServerSocket ss = new ServerSocket(port);
We specify the port we want to listen on. Then we call the method .accept(), which will wait for a client to connect to the port, then return a socket representing our side of the connection:
	ServerSocket ss = new ServerSocket(port);
	Socket connection = ss.accept();
Once we have established a connection, we can send data back and forth across the socket. To do this we simply use .getInputStream and .getOutputStream on the socket, to get the appriorate streams.

Then sending data accross the network is no different than normal java i/o. Note, however, you should explicitly flush() the OutputStream after sending a group of data to make the data actually go across the network immediately.

You can wrap the basic streams in any stream you want, handle data as you like. A simple way of handling this is to wrap a BufferedReader and PrintWriter around the streams, then send each until of data using a PrintWriter.println() and BufferedReader.readLine(). These aren't the most efficient network trafficwise, but are recommend for beginners to network programming. (It is also the method used by most of Java's examples).

Also don't forget to close() your sockets!

Multithreaded Serving

Say you want to write a real server that handles an arbitary number of connections at the same time. To do this, we need to spawn a thread for each new connection. We generally implement a class to do the work for each connection. Let's assume that we have such a class, Worker, that implements runnable and its constructor takes the established socket for the client. Then we just need code like this:
	ServerSocket ss = new ServerSocket(port);
	while(true)
	{
		Socket connection = ss.accept();
		Thread worker = new Thread(new Worker(connection));
		worker.start();
	}
Exercise

Write a multithreaded server that expects to receive pair of integers. It adds the integers and sends the result to its client.

Write a simple client that sends randon numbers to your server.

To help you, here is a test client/server pair (they use port 13958): Server
Client

Due at the end of class.