previous | start | next

Server Sockets in Java

A server is potentially far more complex than a client, although Java makes it easy to code a simple example:
import java.io.*;
import java.net.*;
class SillyServer {
    public static void main(String argv[]) throws Exception
    {
        String incoming;
        String outgoing;
        ServerSocket servSock = new ServerSocket(7277);
        
        while(true) {
            Socket connectedSocket = servSock.accept();
            DataInputStream fromClient =
                new DataInputStream(
                    connectedSocket.getInputStream());
            DataOutputStream toClient =
                new DataOutputStream(
                    connectedSocket.getOutputStream());
            incoming = fromClient.readLine();
            outgoing = incoming.toUpperCase() + "\n";
            toClient.writeBytes(outgoing);
            connectedSocket.close();
        }
    }
}
Lecture 9: Socket Programming Interface Copyright © 2005 P.Scott, La Trobe University Bendigo.


previous | start | next