什么是WebSocket
WebSocket 协议本质上是一个基于 TCP 的协议。为了建立一个 WebSocket 连接,客户端浏览器首先要向服务器发起一个 HTTP 请求,这个请求和通常的 HTTP 请求不同,包含了一些附加头信息,其中附加头信息”Upgrade: WebSocket”表明这是一个申请协议升级的 HTTP 请求,服务器端解析这些附加的头信息然后产生应答信息返回给客户端,客户端和服务器端的 WebSocket 连接就建立起来了,双方就可以通过这个连接通道自由的传递信息,并且这个连接会持续存在直到客户端或者服务器端的某一方主动的关闭连接。
为什么要用WebSocket
在项目中,常规都是前端向后端发送请求后,才能获取到后端的数据。但是在一些及时消息的处理上,这样的处理效率有些捉襟见肘;在以往获得即时数据时,比较low的方案就是ajax轮询查询;或者可以使用socket的长连接;但是这些在实际的操作上都比较消耗资源;而websocket在这方面有效的解决这个问题--WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通信——允许服务器主动发送信息给客户端,客户端接收到消息可即时对消息进行处理。
webscoket 在项目中的使用
服务端(Java)
package org.meal.controller;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websockets")
public class WebscoketsController extends HttpServlet{
//concurrent包的线程安全Set,用来存放每个客户端对应的MyWebSocket对象。若要实现服务端与单一客户端通信的话,可以使用Map来存放,其中Key可以为用户标识
private static CopyOnWriteArraySet<WebscoketsController> webSocketSet = new CopyOnWriteArraySet<WebscoketsController>();
//这个session不是Httpsession,相当于用户的唯一标识,用它进行与指定用户通讯
private javax.websocket.Session session=null;
public void doGet(HttpServletRequest request, HttpServletResponse response,long deskId,long shopid) throws ServletException,IOException {
//发送更新信号
sendMessage(deskId,shopid);
//response.sendRedirect("http://localhost:8080");
}
public void doPost(HttpServletRequest request,HttpServletResponse reponse) throws ServletException, IOException {
doGet(request,reponse);
}
/**
* @OnOpen allows us to intercept the creation of a new session.
* The session class allows us to send data to the user.
* In the method onOpen, we'll let the user know that the handshake was
* successful.
* 建立websocket连接时调用
*/
@OnOpen
public void onOpen(Session session){
System.out.println("Session " + session.getId() + " has opened a connection");
try {
this.session=session;
webSocketSet.add(this); //加入set中
session.getBasicRemote().sendText("Connection Established");
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* When a user sends a message to the server, this method will intercept the message
* and allow us to react to it. For now the message is read as a String.
* 接收到客户端消息时使用,这个例子里没用
*/
@OnMessage
public void onMessage(String message, Session session){
System.out.println("Message from " + session.getId() + ": " + message);
}
/**
* The user closes the connection.
*
* Note: you can't send messages to the client from this method
* 关闭连接时调用
*/
@OnClose
public void onClose(Session session){
webSocketSet.remove(this); //从set中删除
System.out.println("Session " +session.getId()+" has closed!");
}
/**
* 注意: OnError() 只能出现一次. 其中的参数都是可选的。
* @param session
* @param t
*/
@OnError
public void onError(Session session, Throwable t) {
t.printStackTrace();
}
/**
* 这个方法与上面几个方法不一样。没有用注解,是根据自己需要添加的方法。
* @throws IOException
* 发送自定义信号,“1”表示告诉前台,数据库发生改变了,需要刷新
*/
public void sendMessage(long deskId,long shopid) throws IOException{
String id=String.valueOf(deskId);
String shop=String.valueOf(shopid);
String ids=id+","+shop;
//群发消息
for(WebscoketsController item: webSocketSet){
try {
item.session.getBasicRemote().sendText(ids);
} catch (IOException e) {
e.printStackTrace();
continue;
}
}
}
}
//在传送消息时,需要调用webscoket的doget函数
WebscoketsController controller2 = new WebscoketsController();
try {
controller2.doGet(request, response, list.get(list.size()-1).getDeskId(), shopId);
} catch (ServletException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
客户端(VUE)
created () {
this.initWebSocket()
},
methods: {
// weosocket
initWebSocket(){ //初始化weosocket
const wsuri = "ws://localhost:8080";
this.websock = new WebSocket(wsuri);
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
websocketonopen(){ //连接建立之后执行send方法发送数据
console.log('send')
this.webEach('链接成功')
},
websocket(){//连接建立失败重连
console.log('重连')
this.initWebSocket();
},
websocketonmessage(e){ //数据接收
console.log('数据接收')
console.log(e)
this.webEach(e.data)
},
websocketsend(Data){//数据发送
console.log('数据发送')
},
websocketclose(e){//关闭
console.log('断开连接',e);
}
<!--在页面中展示所获取的数据-->
webEach (data) {
console.log(data)
}
}