-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathServerChat.java
More file actions
84 lines (80 loc) · 1.39 KB
/
ServerChat.java
File metadata and controls
84 lines (80 loc) · 1.39 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
82
83
84
import java.io.*;
import java.net.*;
import java.util.*;
public class ServerChat
{
ServerSocket ss;
Socket s;
ArrayList al=new ArrayList();
public ServerChat()
{
try
{
System.out.println("Server started");
ss = new ServerSocket(1034);
int count=0;
while(true)
{
s = ss.accept();
count++;
System.out.println("CLIENT "+count+"CONNECTED");
al.add(s);
MyThread r=new MyThread(s,al);
Thread t=new Thread(r);
t.start();
}
}catch(Exception e)
{ System.out.println(e); }
}
public static void main(String[] args) {
new ServerChat();
}
}
class MyThread implements Runnable
{
Socket s;
ArrayList al;
public MyThread(Socket s,ArrayList al)
{
this.s=s;
this.al=al;
}
public void run()
{
try{
String s1;
DataInputStream dis = new DataInputStream(s.getInputStream());
do
{
s1=dis.readUTF();
System.out.println(s1);
if(!s1.equals("stop"))
{
tellEveryone(s1);
}
else
{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(s1);
dos.flush();
al.remove(s);
}
}while(!s1.equals("stop"));
}catch(Exception e){}
}
public void tellEveryone(String s1)
{
try
{
Iterator i=al.iterator();
while(i.hasNext())
{
Socket sc=(Socket)i.next();
DataOutputStream dos = new DataOutputStream(sc.getOutputStream());
dos.writeUTF(s1);
dos.flush();
//System.out.println("CLIENT");
}
}catch(Exception e){}
}
}