Echo server: Difference between revisions

Content added Content deleted
m (→‎{{header|Java}}: formatting)
Line 550: Line 550:
import java.net.Socket;
import java.net.Socket;


public class EchoServer {

public class EchoServer
{
ServerSocket serverSocket;
ServerSocket serverSocket;
public EchoServer(){
public EchoServer(){
}
}
public void start()
public void start() {
{
try {
try {
serverSocket = new ServerSocket(12321);
serverSocket = new ServerSocket(12321);
Line 567: Line 564:
} catch (IOException e) {
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
}finally{
} finally {
try {
try {
System.out.println("closing server socket");
System.out.println("closing server socket");
Line 578: Line 575:
}
}
public static void main(String[] args)
public static void main(String[] args) {
{
EchoServer es = new EchoServer();
EchoServer es = new EchoServer();
es.start();
es.start();
Line 590: Line 586:
Socket clientSocket;
Socket clientSocket;
public ClientHandler(Socket s){
public ClientHandler(Socket s) {
connectionId = numConnections++;
connectionId = numConnections++;
System.out.println("handling connection, #" + connectionId);
System.out.println("handling connection, #" + connectionId);
Line 599: Line 595:
PrintWriter out = null;
PrintWriter out = null;
BufferedReader in = null;
BufferedReader in = null;
try{
try {
out = new PrintWriter(clientSocket.getOutputStream(), true);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Line 611: Line 607:
break;
break;
}
}
} catch(Exception e) {
}
catch(Exception e){
e.printStackTrace();
e.printStackTrace();
}finally{
} finally {
out.close();
out.close();
try {
try {
Line 624: Line 619:
}
}
}
}
}
}
}</lang>
}</lang>