server
This commit is contained in:
parent
19f9cd84de
commit
b0fcb7c79c
|
@ -0,0 +1,71 @@
|
|||
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());
|
||||
|
||||
ClientHandler clientsock = new ClientHandler(client);
|
||||
new Thread(clientSock.start());
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
} finally {
|
||||
if (server != null) {
|
||||
try {
|
||||
server.close();
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static class ClientHandler implements Runnable {
|
||||
|
||||
private final Socket clientSocket;
|
||||
|
||||
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();
|
||||
clientSocket.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue