Java Reference
In-Depth Information
You want to create a server application that will listen for connections from a remote
client.
Solution
Set up a server-side application that makes use of java.net.ServerSocket to
listen for requests on a specified port. The following Java class is representative of one
that would be deployed onto a server, and it listens for incoming requests on port
1234 . When a request is received, the incoming message is printed to the command
line and a response is sent back to the client.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServer {
public static void main(String a[]) {
final int httpd = 1234;
ServerSocket ssock = null;
try {
ssock = new ServerSocket(httpd);
System.out.println("have opened port 1234
locally");
Socket sock = ssock.accept();
System.out.println("client has made socket
connection");
communicateWithClient(sock);
System.out.println("closing socket");
} catch (Exception e) {
System.out.println(e);
} finally {
Search WWH ::




Custom Search