-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathChatServer.java
105 lines (78 loc) · 2.21 KB
/
ChatServer.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
94
95
96
97
98
99
100
101
102
103
104
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class ChatServer implements Runnable {
private ArrayList<Socket> connected = new ArrayList<Socket>();
private ArrayList<String> users = new ArrayList<String>();
private HashMap<Socket,String> data = new HashMap<Socket,String>();
static final int SERVER_PORT = 17000;
private String host;
private ServerSocket server;
private Timer timer;
public ChatServer()
{
Thread t = new Thread(this);
t.start();
timer = new Timer(users);
Thread timeThread = new Thread(timer);
timeThread.start();
}
@Override
public void run() {
Socket s;
ChatClientThread client;
try
{
server = new ServerSocket(SERVER_PORT);
host = InetAddress.getLocalHost().getHostName();
}
catch(IOException e)
{
System.out.println(e);
JOptionPane.showMessageDialog(null, "Unable to create the server socket.");
System.exit(0);
}
System.out.println("Server has been started at host: " + host);
while(true)
{
try {
s = server.accept();
connected.add(s);
timer.reset();
System.out.println("Client connected from: "+ s.getLocalAddress().getHostName());
addUser(s);
client = new ChatClientThread(s,connected,users,data,timer);
Thread clientT = new Thread(client);
clientT.start();
} catch (IOException | ClassNotFoundException e) {
System.out.println("Server error - unable to connect to client.");
}
}
}
public void addUser(Socket s) throws IOException, ClassNotFoundException
{
Scanner input = new Scanner(s.getInputStream());
String name = input.nextLine();
users.add(name);
data.put(s,name);
for(int i=0;i<connected.size();i++)
{
Socket tmps = connected.get(i);
PrintWriter output = new PrintWriter(tmps.getOutputStream(),true);
output.println("!%#&" + users);
output.flush();
}
}
public static void main(String[] args) throws IOException
{
new ChatServer();
}
}