// SimpleServerSocket
import java.net.*;
import java.io.*;
/**
* This is a simple server socket example with two static methods:
* server deamon waiting for clients and service provider.
* @author Jeff Zhuk
*/
public class SimpleServerSocket {
// Open server socket and listen for client requests
public static void startServerDeamon(int iPort)
{
ServerSocket server = null;
// register server socket on the port = iPort
try {
server = new ServerSocket(iPort);
} catch (IOException e) {
System.out.err("Server socket failure: " + e);
return;
}
Socket client = null;
DataInputStream in = null;
PrintStream out = null;
// start indefinite loop waiting for clients to accept
while(true)
{
try {
// listen for a client connection to accept
client = server.accept();
// connect input/output streams to the socket
in = new DataInputStream(client.getInputStream());
out = new PrintStream(client.getOutputStream());
// read client request, a string is expected, not bytes!
String clientRequest = in.readLine();
// process this client request and get a response for a client
String response = serviceMethod(clientRequest, in); // service
// Send the response back to the client. It's a string operation.
out.println(response); // success or failure
// close the client connection, keep alive the server socket
client.close();
} catch (IOException e) {
System.out.err("Server socket failure: " + e);
}
}
}
// The simplest example of the service on the server side
public static String serviceMethod(String iRequest, DataInputStream iStream) {
// find out what service is needed
// read additional info from the input stream if necessary
// provide the service
}
}
Back To Java Networking