首先websocket后台需要在web服务器运行,所以先搭建一个web项目。websocket需要依赖其他的jar包,引入依赖
<dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>7.0</version> <scope>provided</scope> </dependency>
新建一个类,该类建立一个服务端点 ServerEndpoint
import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; /** * @author Rice * @create 2020/06/24 15:56 */ @ServerEndpoint("/ws/{sid}") public class WSServer { private Session session ; private static ConcurrentHashMap<String,Session> ss = new ConcurrentHashMap<String,Session>(); private int oln ; @OnOpen public void onOpen(Session session,@PathParam("sid") String sid){ oln++; this.session = session; ss.put(sid,session); } @OnMessage public void onMessage(String message ,Session session,@PathParam("sid") String sid ) throws IOException { Msg msg = Msg.getInstance(message); msg.setUser(sid); if(msg.getTid()==1){ privateChat(msg); return ; } } @OnClose public void onClose(@PathParam("sid") String sid){ oln--; ss.remove(sid); } @OnError public void onError(Session session ,Throwable error){ System.out.println(error); } private void privateChat(Msg msg) throws IOException { if (ss.containsKey(msg.getTsid())){ Session ts = ss.get(msg.getTsid()); ts.getBasicRemote().sendText(Msg.forwordMSg(msg)); }else{ this.session.getBasicRemote().sendText("对方不在线"); } } }
前端(客户端点):
ws = new WebSocket("ws://localhost:8080/wws/ws/"+_this.luser)
ws.onmessage=function(event){
let rm = JSON.parse(event.data);
if(!_this.msgs[rm.user]){
_this.$set(_this.msgs,rm.user,new Array());
}
_this.msgs[rm.user].push(rm.user+": "+rm.msg);
}
当客户端点调用new Websocket时,会发起和服务端的连接。当websocekt的readystate变为1时,会触发后端onopen事件,此时一般会将建立连接的session加入到管理的Map中,记录session的名字和session.以此方便进行消息的转发。
当客户端readystate=1(连接成功),客户端可以进行发消息,关闭连接。当客户端调用websocket.send(String msg),后台会触发onMessage方法并且把消息以及发消息的session传入到该方法中进行处理。通常客户端发送的消息需要自行规定数据报格式,如JSON,给后台进行解析。
客户端点同样的需要进行onmessage方法的处理,当服务端往客户端session发送消息,同样会触发客户端的onmessage方法。以此达到即时沟通