Use Java-WebSocket to implement a simple chat server.
Java codes: 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
74import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
/**
* A simple WebSocketServer implementation. Keeps track of a "chatroom".
*/
public class ChatServer extends WebSocketServer {
public ChatServer(int port) {
super(new InetSocketAddress(port));
}
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conn.send("Welcome to the server!"); // This method sends a message to the new client
broadcast("new connection: " + handshake.getResourceDescriptor()); // This method sends a message to all clients connected
System.out.println(conn.getRemoteSocketAddress().getAddress().getHostAddress() + " entered the room!");
}
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
broadcast(conn + " has left the room!");
System.out.println(conn + " has left the room!");
}
public void onMessage(WebSocket conn, String message) {
broadcast(message);
System.out.println(conn + ": " + message);
}
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
if (conn != null) {
// some errors like port binding failed may not be assignable to a specific websocket
}
}
public void onMessage(WebSocket conn, ByteBuffer message) {
broadcast(message.array());
System.out.println(conn + ": " + message);
}
public static void main(String[] args) throws InterruptedException, IOException {
ChatServer s = new ChatServer(8887);
s.start();
BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String in = sysin.readLine();
s.broadcast(in);
if (in.equals("exit")) {
s.stop(1000);
break;
}
}
}
public void onStart() {
System.out.println("Server started!");
setConnectionLostTimeout(0);
setConnectionLostTimeout(100);
}
}
JavaScript codes: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15ws = new WebSocket("ws://localhost:8887");
ws.onopen = function () {
ws.send('hello from client')
};
ws.onmessage = function (evt) {
var msg = evt.data
console.log(`received msg is ${msg}`)
}
ws.onclose = function () {
console.log("closed")
}
Then run the code below in the console window.
1 | ws.send('hello') |