2024-11-12 08:55:12 +00:00
|
|
|
import java.io.*;
|
|
|
|
import java.net.*;
|
|
|
|
|
|
|
|
class Server {
|
|
|
|
public static void main(String[] args) {
|
|
|
|
ServerSocket server = null;
|
|
|
|
try {
|
|
|
|
// start server
|
|
|
|
server = new ServerSocket(8080);
|
|
|
|
server.setReuseAddress(true);
|
|
|
|
|
|
|
|
while (true) {
|
|
|
|
Socket client = server.accept();
|
|
|
|
System.out.println("New client: " + client.getInetAddress().getHostAddress());
|
|
|
|
|
2024-11-12 09:13:53 +00:00
|
|
|
ClientHandler clientSock = new ClientHandler(client);
|
|
|
|
new Thread(clientSock).start();
|
2024-11-12 08:55:12 +00:00
|
|
|
}
|
|
|
|
} catch (IOException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
} finally {
|
|
|
|
if (server != null) {
|
|
|
|
try {
|
|
|
|
server.close();
|
|
|
|
} catch (IOException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private static class ClientHandler implements Runnable {
|
|
|
|
|
2024-11-12 09:13:53 +00:00
|
|
|
private Socket clientSocket;
|
2024-11-12 08:55:12 +00:00
|
|
|
|
|
|
|
public ClientHandler(Socket socket) {
|
|
|
|
this.clientSocket = socket;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void run() {
|
|
|
|
PrintWriter out = null;
|
|
|
|
BufferedReader in = null;
|
|
|
|
try {
|
|
|
|
out = new PrintWriter(clientSocket.getOutputStream(), true);
|
|
|
|
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
|
|
|
|
|
|
|
|
String line;
|
|
|
|
while ((line = in.readLine()) != null) {
|
|
|
|
System.out.printf("From the client: %s\n", line);
|
|
|
|
out.println(line);
|
|
|
|
|
|
|
|
}
|
|
|
|
} catch (IOException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
} finally {
|
|
|
|
try {
|
|
|
|
if (out != null) {
|
|
|
|
out.close();
|
|
|
|
}
|
|
|
|
if (in != null) {
|
|
|
|
in.close();
|
2024-11-12 09:13:53 +00:00
|
|
|
System.out.println("closing socket " + clientSocket.getInetAddress().getHostAddress());
|
2024-11-12 08:55:12 +00:00
|
|
|
clientSocket.close();
|
|
|
|
}
|
|
|
|
} catch (IOException e) {
|
|
|
|
e.printStackTrace();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|