WebSocket干货-1
首先Maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
自动配置
@Configuration public class SocketClientConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
ServerEndpointExporter 翻译过来是服务器端点导出器 具体是做什么不知道 就当是自动注入需要的配置类吧
千呼万唤使出来 -ServerEndpoint
这个就是端口服务了 先贴代码
@ServerEndpoint("/client/{sid}")
public class ISocketClientService {
private static Integer onCount=0;
private Session session;
private String sid;
private static CopyOnWriteArraySet<ISocketClientService> webSocketSet = new CopyOnWriteArraySet<ISocketClientService>();
/**
* 连接成功建立的方法
* @param session
* @param sid
*/
@OnOpen
public void onOpen(Session session, @PathParam("sid")String sid){
this.session=session;
this.sid=sid;
webSocketSet.add(this);
log.info("有新窗口开始监听:"+sid+",当前在线人数为" + ++onCount);
try {
this.session.getBasicRemote().sendText("登录成功. 当前账户sid为:"+this.sid);
} catch (IOException e) {
log.error("消息发送出错");
e.printStackTrace();
}finally {
}
}
@OnClose
public void onClose(){
webSocketSet.remove(this); //从set中删除
--onCount; //在线数减1
log.info("有一连接关闭!当前在线人数为" + onCount);
}
@OnMessage
public void OnMessage(String message, Session session){
log.info("收到来自窗口"+sid+"的信息:"+message);
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误");
error.printStackTrace();
}
public void sendMsg(String messagem,String sid){
//判断sid是否存在
try {
this.session.getBasicRemote().sendText(this.sid);
} catch (IOException e) {
e.printStackTrace();
}
}
}
前端JS调用
<script>
var sockest;
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
console.log("您的浏览器支持WebSocket");
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
//等同于
index = new WebSocket("ws://localhost:8823/client/2");
sockest=index;
//socket = new WebSocket("${basePath}websocket/${cid}".replace("http","ws"));
//打开事件
index.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
index.onmessage = function(msg) {
console.log(msg.data);
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
index.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
index.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
//离开页面时,关闭socket
//jquery1.8中已经被废弃,3.0中已经移除
// $(window).unload(function(){
// socket.close();
//});
}
function sendMsg() {
console.log("sendmsg");
this.sockest.send("页面发送来数据了 快接收啊。")
}
</script>
至此一个WebSocket的框子就搭好了
下一步实现
1对1聊天
多人聊天

浙公网安备 33010602011771号