WebSocket 协议本质上是一个基于 TCP 的协议。为了创建一个 WebSocket 链接,客户端浏览器首先要向服务器发起一个 HTTP 请求,这个请求和一般的 HTTP 请求不一样,包含了一些附加头信息,其中附加头信息”Upgrade: WebSocket”代表这是一个申请协议升级的 HTTP 请求,服务器端解析这些附加的头信息而后产生应答信息返回给客户端,客户端和服务器端的 WebSocket 链接就创建起来了,双方就能够经过这个链接通道自由的传递信息,而且这个链接会持续存在直到客户端或者服务器端的某一方主动的关闭链接。html
在项目中,常规都是前端向后端发送请求后,才能获取到后端的数据。可是在一些及时消息的处理上,这样的处理效率有些捉襟见肘;在以往得到即时数据时,比较low的方案就是ajax轮询查询;或者可使用socket的长链接;可是这些在实际的操做上都比较消耗资源;而websocket在这方面有效的解决这个问题--WebSocket协议是基于TCP的一种新的网络协议。它实现了浏览器与服务器全双工(full-duplex)通讯——容许服务器主动发送信息给客户端,客户端接收到消息可即时对消息进行处理。前端
服务端(Java)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)react
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)
}
}
复制代码