CS 596 Client-Server Programming
For TCP servers we use the ServerSocket class
ServerSocket constructors:
Note: if the port is 0, a random port # will be picked.
ServerSocket methods:
Recall simple algorithm for TCP server:
Create accepting socket loop forever wait for new connection handle connection end loop
Java equivalent:
import java.net.*;
class SimpleTCPServer
{
public static void main(String a[])
throws Exception;
{
ServerSocket acceptor = new ServerSocket(0);
System.out.println("On port " +
acceptor.getLocalPort());
while (true)
{
Socket client = acceptor.accpet();
// Do stuff here...
client.close();
}
}
}
Use the DatagramSocket class.
We have already seen this in use in the datagram client from previous lecture
but now the send and receive are swapped.
import java.net.*;
class SimpleUDPServer
{
public static void main(String args[])
throws Exception
{
DatagramSocket socket = new
DatagramSocket();
while (true)
{
byte[] data = new byte[100];
DatagramPacket packet = new
DatagramPacket(data, data.length);
socket.receive(packet);
InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(data,
data.length, address, port);
socket.send(packet);
}
}
}