Echo server: Difference between revisions

→‎{{header|Java}}: Unbloat Java code
(→‎{{header|Java}}: Unbloat Java code)
Line 1,289:
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
 
public class EchoServer {
ServerSocket serverSocket;
public EchoServer(){
}
public void start() {
try {
serverSocket = new ServerSocket(12321);
while(true){
Thread clientThread = new Thread(new ClientHandler(serverSocket.accept()));
clientThread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
System.out.println("closing server socket");
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
EchoServer es = new EchoServer();
es.start();
}
}
 
public static void main(String[] args) throws IOException {
class ClientHandler implements Runnable {
serverSocket try (ServerSocket listener = new ServerSocket(12321);) {
private static int numConnections;
while (true) {
private int connectionId = 0;
Socket conn = listener.accept();
Socket clientSocket;
Thread clientThread = new Thread(() -> handleClient(conn));
clientThread.start();
public ClientHandler(Socket s) {
}
connectionId = numConnections++;
}
System.out.println("handling connection, #" + connectionId);
}
clientSocket = s;
}
 
private static void handleClient(Socket connArg) {
public void run() {
Charset utf8 = StandardCharsets.UTF_8;
PrintWriter out = null;
 
BufferedReader in = null;
try (Socket conn = connArg) {
try {
BufferedReader in = new BufferedReader(
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader( new InputStreamReader(clientSocketconn.getInputStream(), utf8));
 
String inputLine, outputLine;
PrintWriter out = new PrintWriter(
while((inputLine = in.readLine()) != null){
new OutputStreamWriter(conn.getOutputStream(), utf8),
outputLine = inputLine;
true);
System.out.println("received: " + outputLine);
 
out.write(outputLine+"\n");
String line;
out.flush();
while ((inputLineline = in.readLine()) != null) {
if (outputLine.equals("exit"))
out.println(line);
break;
}
}
} catch (ExceptionIOException e) {
e.printStackTrace();
}
} finally {
}
out.close();
try {
in.close();
clientSocket.close();
System.out.println("closing connection, #" + connectionId);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}</lang>