个人笔记
这里是引用
一。什么是WebSocket
一个基于tcp的全双工实时通信协议(还有很多相似 sse spdy webrtc)
握手阶段还是利用http协议 可以一次握手持续通讯
Websocket 使用ws 或者 wss的统一资源标识符 wss代表加密
upgrade 协议升级 菜鸟教程图
二、小案例两个页面互相发送文字
pom配置
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.java-websocket</groupId>
<artifactId>Java-WebSocket</artifactId>
<version>1.3.5</version>
</dependency>
服务器端
@ServerEndpoint("/websocket/server/{userid}")
public class WebSocketServer {
static Map<String,WebSocketServer> sessions=new HashMap<>();
public String userid;
public Session session;
@OnOpen
public void onOpen(@PathParam("userid") String userid, Session session){
this.userid=userid;
this.session=session;
sessions.put(userid,this);
System.out.println("接收到请求:"+userid);
}
@OnClose
public void onClose(Session session){
sessions.remove(userid);
}
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("服务器收到客户端的消息:"+message);
String[] split = message.split("--");
String s = split[0];
message = split[1];
this.sendMessage(s,message);
}
public void sendMessage(String userid,String message){
try {
sessions.get(userid).session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端 2
<%--
Created by IntelliJ IDEA.
User: 15836
Date: 2021/11/8
Time: 9:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="/resources/jquery-3.5.0.min.js"></script>
</head>
<body>
<div id="msg"></div>
<input id="mb" type="text" placeholder="请输入发送明目标">
<input id="xx" type="text" placeholder="请输入发送消息">
<input type="button" value="发送" id="sendBtn">
</body>
<script>
var ws=new WebSocket('ws://localhost:8080/websocket/server/分站');
$("#sendBtn").click(function() {
var xx = $("#xx").val();
var mb=$("#mb").val();
ws.send(mb+"--"+xx);
})
ws.readyState
ws.onopen=function () {
console.log(ws.readyState)
}
ws.onmessage=function(msg){
console.log(msg);
$("#msg").append(msg.data+"</br>");
}
</script>
</html>
客户端 1
<%--
Created by IntelliJ IDEA.
User: 15836
Date: 2021/11/8
Time: 9:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="/resources/jquery-3.5.0.min.js"></script>
</head>
<body>
<div id="msg"></div>
<input id="mb" type="text" placeholder="请输入发送明目标">
<input id="xx" type="text" placeholder="请输入发送消息">
<input type="button" value="发送" id="sendBtn">
</body>
<script>
var ws=new WebSocket('ws://localhost:8080/websocket/server/车载');
$("#sendBtn").click(function() {
var xx = $("#xx").val();
var mb=$("#mb").val();
ws.send(mb+"--"+xx);
})
ws.onopen=function () {
console.log(ws.readyState)
}
ws.onmessage=function(msg){
console.log(msg);
$("#msg").append(msg.data+"</br>");
}
</script>
</html>
效果图 注意 学习下 socket.io
|