-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
81 lines (68 loc) · 2.29 KB
/
ChatServer.java
File metadata and controls
81 lines (68 loc) · 2.29 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.io.*;
import java.util.*;
import java.net.*;
/**
* ChatServer.java
*
* Copyright 2015 David Camacho
*
* This program creates the server so the users can connect the server and send
* strings to everyone connected to the server.
*
*/
public class ChatServer{
// gets the clients so that we can send the string to each one
public ArrayList<ServerThread> st = new ArrayList<ServerThread>();
public static void main(String[] args){
new ChatServer();
}
/**
* The ChatServer constructor gets who is connected and then adds them to the arraylist and then
* we start the thread.
*/
public ChatServer(){
ServerSocket ss = null;
try{
ss = new ServerSocket(16457);
Socket socket = null;
while(true){
socket = ss.accept();
ServerThread threaded = new ServerThread(socket);
st.add(threaded);
threaded.start();
}
}
catch(Exception e){
System.out.println("An Error occurred");
}
}
/**
* ServerThread has the run method that starts the thread which gets the
* strings from the clients and send them to everyone connected to the server.
*/
class ServerThread extends Thread{
Socket s = null;
String clientMsg;
PrintWriter pw;
BufferedReader br;
public ServerThread(Socket _socket){
s = _socket; // gets the socket from the other class
}
public void run(){
try{
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
while((clientMsg = br.readLine()) != null){ // loops while it is reading the message
System.out.println("Server read: "+ clientMsg);
for(ServerThread get : st){ // for loop to iterate through each client and send them the string
get.pw.println(clientMsg); //to clients
get.pw.flush();
}
}
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
}