1. websocket
这篇博主写的比较清楚:
https://www.cnblogs.com/jingmoxukong/p/7755643.html
1. 客户端实现
(1)先画一个简单页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<div>
姓名: <input id="name"/> 联系人: <input id="anther"/>
<button onclick="initWebSocket()">登录</button>
<br/>
输入: <input id="ipt" />
<button onclick="send()">发送</button>
<br/>
<div id="chatList"></div>
</div>
</body>
</html>
页面长这样:
(2) 编写js
//初始化一个 WebSocket 对象
var g_ws;
function $(id) {
return document.getElementById(id);
}
function initWebSocket() {
var name = $("name").value;
g_ws = new WebSocket("ws://localhost:7545/websocket/websocket/" + name);
// 建立 web socket 连接成功触发事件
g_ws.onopen = function () {};
// 接收服务端数据时触发事件
g_ws.onmessage = function (evt) {
var received_msg = JSON.parse(evt.data);
$("chatList").innerHTML += '<div>' + received_msg.msg + '</div>';
};
}
function send() {
var msg = $("ipt").value;
var name = $("anther").value;
g_ws.send(JSON.stringify({
to: name,
msg: msg
}));
}
2. 服务端实现
(1) 依赖包
核心依赖:javax.websocket-api
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
(2) java实现代码
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import com.alibaba.fastjson.JSONObject;
@ServerEndpoint("/websocket/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.parseObject(message);
if (!jsonTo.get("to").equals("All")) {
sendMessageTo(message, jsonTo.get("to").toString());
} else {
sendMessageAll(message);
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
for (WebSocket item : clients.values()) {
if (item.username.equals(To))
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}
3. 效果
下面是基础效果: