jee websocket搭建总结

时间:2022-10-19 16:05:45

1、使用框架spring+springmvc+mybatis+jdk7+tomcat7+maven

2、基本原理:

jee websocket搭建总结

    a. WebSocket协议是一种双向通信协议,它建立在TCP之上,同http一样通过TCP来传输数据,但是 它和http最大的不同有两点:

1.WebSocket是一种双向通信协议,在建立连接后,WebSocket服务器和Browser/UA都能主动地向对方发送或接收数据,就像Socket一样,不同的是WebSocket是一种建立在Web基础上的一种简单模拟Socket的协议;

2.WebSocket需要通过握手连接,类似于TCP它也需要客户端和服务器端进行握手连接,连接成功后才能相互通信。

    b.struts   和 websocket  是2条处理请求的路,被struts 匹配上了 ,自然就到不了 websocket的处  理逻辑,(http和ws是两种不同的请求协议,注意框架的拦截器(过滤器))

3、客户端:

<html>
<head>
<title>Title</title>
<style> div {
margin-left: auto;
margin-right: auto;
} </style>
</head>
<body onLoad="startWebSocket()">
<script type="text/javascript">
function clog(title) {
console.log(title);
} var ws = null;
function startWebSocket() { if ('WebSocket' in window) { try {
ws = new WebSocket("ws://127.0.0.1:80/websocket/tui");
} catch (e) {
clog("1");
}
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket("ws://127.0.0.1:80/websocket/tui");
} else {
clog("websocket not support");
} ws.onmessage = function (evt) {
say(evt.data);
}; ws.onclose = function (evt) {
clog("close!");
}; ws.onopen = function (evt) {
clog("open");
};
} function sendMsg() {
ws.send(document.getElementById('writeMsg').value);
} function say(msg) {
var div = document.createElement("div");
div.innerHTML = msg;
document.body.appendChild(div);
} </script>
<div onClick="say('d')">WebSocket聊天室</div>
<div style="border:1px solid #09F"></div>
<input type="text" id="writeMsg"/>
<input type="button" value="send" onClick="sendMsg()"/> </body>
</html>

4、服务端:

@ServerEndpoint(value = "/websocket/tui")
public class WebSocketDemo{
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set<WebSocketDemo> connections = new HashSet<>(); private final String nickname;
private Session session; public WebSocketDemo() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
} //建立连接
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
System.out.println(message);
} //接受消息
@OnMessage
public void incoming(String message) {
System.out.println(message.toString());
//broadcast(filteredMessage);
broadcast(message.toString());
} //客户端关闭了连接
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "has disconnected.");
System.out.println(message);
//broadcast(message);
} //WebSocket服务出错
@OnError
public void onError(Throwable t){
//log.error("Chat Error: " + t.toString(), t);
System.out.println("server has an error!");
} private static void broadcast(String msg) {
for (WebSocketDemo client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
//log.debug("Chat Error: Failed to send message to client", e);
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
// Ignore
}
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
}
}
}
}

注意事项:

1、访问拦截器

2、注意部署的包冲突,例如:javax.websocket只是编译需要,而发布不需要,maven依赖注意适用范围

附:

<!--websocket编译需要,发布不需要-->
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-coyote -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-coyote</artifactId>
<version>7.0.12</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-juli -->
<dependency>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-juli</artifactId>
<version>8.5.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
<dependency>
<groupId>javax.websocket</groupId>
<artifactId>javax.websocket-api</artifactId>
<version>1.1</version>
<scope>provided</scope>
</dependency>