-
Notifications
You must be signed in to change notification settings - Fork 0
/
VerySimpleChatServer.java
68 lines (57 loc) · 2.13 KB
/
VerySimpleChatServer.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
import java.io.*;
import java.net.*;
import java.util.*;
public class VerySimpleChatServer{
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable{
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket){
try{
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch(Exception ex) { ex.printStackTrace(); }
} //close constructor
public void run(){
String message;
try{
while ((message = reader.readLine()) != null ){
System.out.println("read" + message);
tellEveryone(message);
} //close while
} catch(Exception ex) {ex.printStackTrace();}
} // close run
} // close inner class
public static void main(String[] args){
new VerySimpleChatServer().go();
}
public void go(){
clientOutputStreams = new ArrayList();
try{
ServerSocket serverSock = new ServerSocket(5000);
while(true){
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex){
ex.printStackTrace();
}
}// close go
public void tellEveryone(String message){
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()){
try{
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex){
ex.printStackTrace();
}
} // end while
} //close tellEveryOne
}