1、前端:
<javascript>
var socket=null;
if("WebSocket" in window){
//if(window.websocket){}
//注意websocket走的时websocket协议,发请求时协议是ws://
socket=new WebSocket(ws://127.0.0.1:8888/socketTest);
}else{
alert("您的浏览器不支持websocket");
}
//建立连接后要干的事情
socket.onopen=function(event){
console.log("连接已经建立,开始发送消息")
socket.send("message")
}
//关闭连接后要干的事情
socket.onclose=function(){
console.log("连接已经关闭")
}
//收到服务端消息后要干的事情
socket.onmessage=function(message){
console.log("收到来自服务端的消息"+message)
}
//连接出错要干的事情
socket.onerror=function(exception){
console.log("连接出错,请检查网络!")
}
</javascript>
2、后端:
@compenent
@ServerEndPoint()
//@ServerEndPoint将当前类作为一个socket服务器
public class WebSocket{
public Session session;
@onOpen
//@onOpen是socket建立连接时所要执行的方法
public void onOpen(Session session){
this.session=session;
}
@onClose
//@onClose是socket关闭时所要执行的方法
public void onClose(){
system.out.print("连接已经断开")
}
@onMessage
//@onMessage是socket收到消息时时所要执行的方法
public void onMessage(String message){
system.out.print("收到来自客户端的消息:"+message)
}
@onError
//@onError是socket收到消息时时所要执行的方法
public void onError(Throwable error)throws error{
t.printStackTrace();
}
//广播:后端发给前端的消息
public void sendMessage(String message){
this.session.getBasicRemote().sendText(message);
}
}
3、后端还需在IOC容器中注入ServerEndpointExporter,需要在pom文件中添加依赖:spring-boot-starter-websocket
@Configuration
public class SocketConfig{
@Bean
public ServerEndpointExporter getServerEndpoint(){
return new ServerEndpointExporter();
}
}