-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.java
81 lines (70 loc) · 2.13 KB
/
Server.java
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import org.json.simple.JSONObject;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String[] args){
try {
System.out.println("Socket服务器开始运行...");
ServerSocket serverSocket = new ServerSocket(9999);
while (true){
Socket socket = serverSocket.accept();
new Thread(new Server_listen(socket)).start();
new Thread(new Server_send(socket)).start();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
class Server_listen implements Runnable{
private Socket socket;
Server_listen(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
while (true)
System.out.println(ois.readObject());
}catch (Exception e){
e.printStackTrace();
}finally {
try{
socket.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
class Server_send implements Runnable{
private Socket socket;
Server_send(Socket socket){
this.socket = socket;
}
@Override
public void run() {
try {
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in);
while (true){
System.out.print("请输入要发送的内容:");
String string = scanner.nextLine();
JSONObject object = new JSONObject();
extracted(object).put("type","chat");
extracted(object).put("msg",string);
oos.writeObject(extracted(object));
oos.flush();
}
}catch (Exception e){
e.printStackTrace();
}
}
private JSONObject extracted(JSONObject object) {
return object;
}
}