对java程序员方向感兴趣的朋友们,了解过java实现websocket有哪几种方式吗?答案是两种,至于是那两种,可以跟着小编一起来看看哦。
第一种方式:tomcat。
在使用这种方式的时候不需任何别的配置,只需服务端一个处理类。如下所示。
服务器端代码:
package com.Socket;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import net.sf.json.JSONObject;
@ServerEndpoint("/websocket/{username}")
public class WebSocket {
private static int onlineCount = 0;
private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
private Session session;
private String username;
@OnOpen
public void onOpen(@PathParam("username") String username, Session session) throws IOException {
this.username = username;
this.session = session;
addOnlineCount();
clients.put(username, this);
System.out.println("已连接");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.fromObject(message);
if (!jsonTo.get("To").equals("All")){
sendMessageTo("给一个人", jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (WebSocket item : clients.values()) {
if (item.username.equals(To) )
item.session.getAsyncRemote().sendText(message);
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}客户端js代码:
var websocket = null;
var username = localStorage.getItem("name");
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + document.location.host + "/WebChat/websocket/" + username + "/"+ _img);
} else {
alert('当前浏览器 Not support websocket')
}
//连接发生错误的回调方法
websocket.onerror = function() {
setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function() {
setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function(event) {
setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function() {
setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function() {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}在发送消息的时候只需要使用websocket.send("发送消息!"),就可以去触发服务端的onMessage()方法了,在连接的时候,触发服务器端的onOpen()方法,这个时候也可以调用发送消息的方法去发送消息的。在关闭了websocket的时候,会触发服务器端的onclose()方法,这个时候也是可以发送消息的,就是不能发送给自己,毕竟自己都已经关闭了连接,但是可以发送给其他人的。
第二种方式:spring整合。
这种方式它是基于spring mvc框架的。
spring-mvc.xml,需要增加对WebSocketConfig.java类的扫描,还要增加
xmlns:websocket="http://www.springframework.org/schema/websocket" http://www.springframework.org/schema/websocket <a target="_blank" href="http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd">http://www.springframework.org/schema/websocket/spring-websocket-4.1.xsd</a>
客户端代码:
<script type="text/javascript"
src="http://localhost:8080/Bank/js/sockjs-0.3.min.js"></script>
<script>
var websocket;
if ('WebSocket' in window) {
websocket = new WebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
} else if ('MozWebSocket' in window) {
websocket = new MozWebSocket("ws://" + document.location.host + "/Bank/webSocketServer");
} else {
websocket = new SockJS("http://" + document.location.host + "/Bank/sockjs/webSocketServer");
}
websocket.onopen = function(evnt) {};
websocket.onmessage = function(evnt) {
$("#test").html("(<font color='red'>" + evnt.data + "</font>)")
};
websocket.onerror = function(evnt) {};
websocket.onclose = function(evnt) {}
$('#btn').on('click', function() {
if (websocket.readyState == websocket.OPEN) {
var msg = $('#id').val();
//调用后台handleTextMessage方法
websocket.send(msg);
} else {
alert("连接失败!");
}
});
</script>好了,以上就是本篇文章的所有内容了,还想了解更多java入门知识,记得多多关注本站最新消息。