-
Notifications
You must be signed in to change notification settings - Fork 13
/
SocketServer.java
93 lines (79 loc) · 2.66 KB
/
SocketServer.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
82
83
84
85
86
87
88
89
90
91
92
93
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class SocketServer {
ServerSocket server;
Socket sk;
InetAddress addr;
ArrayList<ServerThread> list = new ArrayList<ServerThread>();
public SocketServer() {
try {
addr = InetAddress.getByName("127.0.0.1");
//addr = InetAddress.getByName("192.168.43.1");
server = new ServerSocket(1234,50,addr);
System.out.println("\n Waiting for Client connection");
SocketClient.main(null);
while(true) {
sk = server.accept();
System.out.println(sk.getInetAddress() + " connect");
//Thread connected clients to ArrayList
ServerThread st = new ServerThread(this);
addThread(st);
st.start();
}
} catch(IOException e) {
System.out.println(e + "-> ServerSocket failed");
}
}
public void addThread(ServerThread st) {
list.add(st);
}
public void removeThread(ServerThread st){
list.remove(st); //remove
}
public void broadCast(String message){
for(ServerThread st : list){
st.pw.println(message);
}
}
public static void main(String[] args) {
new SocketServer();
}
}
class ServerThread extends Thread {
SocketServer server;
PrintWriter pw;
String name;
public ServerThread(SocketServer server) {
this.server = server;
}
@Override
public void run() {
try {
// read
BufferedReader br = new BufferedReader(new InputStreamReader(server.sk.getInputStream()));
// writing
pw = new PrintWriter(server.sk.getOutputStream(), true);
name = br.readLine();
server.broadCast("**["+name+"] Entered**");
String data;
while((data = br.readLine()) != null ){
if(data == "/list"){
pw.println("a");
}
server.broadCast("["+name+"] "+ data);
}
} catch (Exception e) {
//Remove the current thread from the ArrayList.
server.removeThread(this);
server.broadCast("**["+name+"] Left**");
System.out.println(server.sk.getInetAddress()+" - ["+name+"] Exit");
System.out.println(e + "---->");
}
}
}