forked from examplehub/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSocketServer.java
More file actions
62 lines (56 loc) · 1.92 KB
/
SocketServer.java
File metadata and controls
62 lines (56 loc) · 1.92 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.examplehub.basics.network;
import com.examplehub.strings.ReverseString;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class SocketServer {
static class ServerHandler implements Runnable {
private final Socket socket;
public ServerHandler(Socket socket) {
this.socket = socket;
}
public void run() {
try (InputStream inputStream = this.socket.getInputStream();
OutputStream outputStream = this.socket.getOutputStream()) {
handle(inputStream, outputStream);
} catch (Exception e) {
try {
this.socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println("client disconnect");
}
}
private void handle(InputStream inputStream, OutputStream outputStream) throws IOException {
var reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
var writer = new BufferedWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8));
writer.write("welcome connect service!\n");
writer.flush();
while (true) {
String line = reader.readLine();
System.out.println("[client]: " + line);
if (line.equals("bye")) {
writer.write("bye\n");
writer.flush();
break;
}
writer.write("ok: " + ReverseString.reverse(line) + "\n");
writer.flush();
}
}
}
public static void main(String[] args) throws IOException {
int port = 6666;
ServerSocket serverSocket = new ServerSocket(port);
System.out.print("server is started! listen on: ");
System.err.print(port);
while (true) {
Socket socket = serverSocket.accept();
System.out.println("connected from " + socket.getRemoteSocketAddress());
new Thread(new ServerHandler(socket)).start();
}
// TODO
}
}