websocket使用方法
websocket是前后端持续通信的一种机制。现在浅析一下:
一。先写前端(这里只用jquery简单实例,不擅长前端)
这里引入了jquery.min.js,这个东西到处都是,仅此而已。
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
<script src="../js/jquery.min.js"></script>
</head>
<body>
欢迎测试websocket!
</body>
</br></br>
<input id="name" type="text"/>
<button onclick="concat()">连接</button>
<br/>
</br>
<input id="text" type="text"/>
<button onclick="send()">发送消息</button>
<button onclick="closeWebSocket()">关闭连接</button>
</br>
<input id="person" type="text"/>
<button onclick="person()">发送消息</button>
<input id="personmessage" type="text"/>
</br>
<div id="message">
</div>
</html>
</body>
<script type="text/javascript">
var websocket = null;
function concat() {
var name = document.getElementById('name').value;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8080/websocket/" + name + "");
} else {
alert('Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function () {
setMessageInnerHTML("socket连接失败");
};
//连接成功建立的回调方法
websocket.onopen = function (event) {
setMessageInnerHTML("socket连接已打开");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
setMessageInnerHTML("socket连接已关闭");
}
//听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
websocket.close();
}
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
document.getElementById('message').innerHTML += innerHTML + "<br/>";
}
//关闭连接
function closeWebSocket() {
websocket.close();
}
//发送消息
function send() {
var message = document.getElementById('text').value;
websocket.send(message);
}
//发送给具体某个人
function person() {
var personmessage = document.getElementById("personmessage").value;
var person = document.getElementById("person").value;
var params = {'personmessage': personmessage, 'person': person};
var url = 'http://localhost:8080/socket/push1';
$.post(url, params, function (result) {
if (result.state == 1) {
//初始化表单数据
doFillFormData(result.data);
} else {
alert(result);
}
});
}
</script>
</html>
这个
websocket = new WebSocket(“ws://localhost:8080/websocket/” + name + “”);就是让前后端连接保持持续通信的。
二 准备后端
①导包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
②写配置类
package com.example.websocket.util;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
③写websocket主类
package com.example.websocket.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
@ServerEndpoint(value = "/websocket/{sname}")
@Component
public class MyWebSocket {
private final static Logger log = LoggerFactory.getLogger(MyWebSocket.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static int onlineCount = 0;
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
//与某个客户端的连接会话,需要通过它来给客户端发送数据
private Session session;
private String name;
/**
* 连接建立成功调用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sname") String sname) {
this.name=sname;
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在线数加1
System.out.println("有新连接加入:"+sname+"!当前在线人数为" + getOnlineCount());
try {
sendMessage(sname,",连接成功,当前时间:" + new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").format(new Date().getTime()));
} catch (IOException e) {
System.out.println("IO异常");
}
}
/**
* 连接关闭调用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //从set中删除
subOnlineCount(); //在线数减1
System.out.println("有一连接关闭!当前在线人数为" + getOnlineCount());
}
/**
* 收到客户端消息后调用的方法
*
* @param message 客户端发送过来的消息*/
@OnMessage
public void onMessage(String message, Session session,@PathParam("sname") String sname) {
System.out.println("来自客户端"+name+"的消息:" + message);
//群发消息
for (MyWebSocket item : webSocketSet) {
try {
//给等陆这机子推送
item.sendMessage(name,message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 发生错误时调用
* */
@OnError
public void onError(Session session, Throwable error) {
System.out.println("发生错误");
error.printStackTrace();
}
/**
* 服务端给客户端发送消息
* @param message
* @throws IOException
*/
public void sendMessage(String name,String message) throws IOException {
this.session.getBasicRemote().sendText(name+"回应消息:"+message+"------------->"+"原酿我这一生不羁放在自由,那会怕有一天会跌倒");
//this.session.getAsyncRemote().sendText(message);
}
/**
* 群发自定义消息
* */
public static void sendInfo(@PathParam("sname") String sname,String message) throws IOException {
for (MyWebSocket item : webSocketSet) {
try {
//这里可以设定只推送给这个sid的,为null则全部推送
if(sname==null) {
item.sendMessage(sname,message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
}else if(item.name.equals(sname)){
item.sendMessage(sname,message);
System.out.println("推送消息给:"+item.name+",消息是===》"+message);
}else {
log.error("此人不存在或没上线!");
continue;
}
} catch (IOException e) {
log.error("在执行"+item+"时遇到错误!");
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
}
这样就可以实现前后端通信了,如果在代码中使用websocket,可以再写一个Controller
例如:
package com.example.websocket.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.IOException;
@Controller
public class IndexController {
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push/{sname}")
public String pushToWeb(@PathVariable String sname, String message) {
try {
MyWebSocket.sendInfo(sname,message);
} catch (IOException e) {
e.printStackTrace();
return "推送失败";
}
return "推送成功"+sname;
}
//推送数据接口
@ResponseBody
@RequestMapping("/socket/push1")
public String pushToWeb1(String person, String personmessage) {
try {
MyWebSocket.sendInfo(person,personmessage);
} catch (IOException e) {
e.printStackTrace();
return "推送失败";
}
return "推送成功,推送给:"+person;
}
}
这样就可以使用了。