forked from TooTallNate/Java-WebSocket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChatServer.java
More file actions
82 lines (71 loc) · 2.19 KB
/
ChatServer.java
File metadata and controls
82 lines (71 loc) · 2.19 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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Set;
import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
/**
* A simple WebSocketServer implementation. Keeps track of a "chatroom".
*/
public class ChatServer extends WebSocketServer {
public ChatServer( int port ) throws UnknownHostException {
super( new InetSocketAddress( port ) );
}
public ChatServer( InetSocketAddress address ) {
super( address );
}
@Override
public void onOpen( WebSocket conn, ClientHandshake handshake ) {
this.sendToAll( "new connection: " + handshake.getResourceDescriptor() );
System.out.println( conn + " entered the room!" );
}
@Override
public void onClose( WebSocket conn, int code, String reason, boolean remote ) {
this.sendToAll( conn + " has left the room!" );
System.out.println( conn + " has left the room!" );
}
@Override
public void onMessage( WebSocket conn, String message ) {
this.sendToAll( message );
System.out.println( conn + ": " + message );
}
public static void main( String[] args ) throws InterruptedException , IOException {
WebSocket.DEBUG = true;
int port = 8887; // 843 flash policy port
try {
port = Integer.parseInt( args[ 0 ] );
} catch ( Exception ex ) {
}
ChatServer s = new ChatServer( port );
s.start();
System.out.println( "ChatServer started on port: " + s.getPort() );
BufferedReader sysin = new BufferedReader( new InputStreamReader( System.in ) );
while ( true ) {
String in = sysin.readLine();
s.sendToAll( in );
}
}
@Override
public void onError( WebSocket conn, Exception ex ) {
ex.printStackTrace();
}
/**
* Sends <var>text</var> to all currently connected WebSocket clients.
*
* @param text
* The String to send across the network.
* @throws InterruptedException
* When socket related I/O errors occur.
*/
public void sendToAll( String text ) {
Set<WebSocket> con = connections();
synchronized ( con ) {
for( WebSocket c : con ) {
c.send( text );
}
}
}
}