WEBSOCKET

实现websocket的两种方式

简单说明1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket2.tomcat的方式需要tomcat7.x,JEE7的支持。3.spring与websocket整合需要spring4.x,并且使用了socketjs,对不支持websocket的浏览器可以模拟websocket使用方式一:tomcat使用这种方式无需别的任何配置,只需服务端一个处理类,服

简单说明

1.两种方式,一种使用tomcat的websocket实现,一种使用spring的websocket

2.tomcat的方式需要tomcat 7.x,JEE7的支持。

3.spring与websocket整合需要spring 4.x,并且使用了socketjs,对不支持websocket的浏览器可以模拟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 c

原创不易,完成人机校验,阅读全文

相关推荐