java后台实现websocket客户端以及服务端

最近遇到一个需求,要求将websocket注册为一个服务在后台运行,持续接收推送。

使用该方法需要引入websocket的jar包。下载地址:https://download.csdn.net/download/qq_39481762/10739165

首先将客户端注册为servlet,这样就可以实现在后台持续接收推送。

public class FaceSocketClientManage extends HttpServlet {

	private static final long serialVersionUID = 1L;
	public static WebSocketClient client;
	public static final String url = "ws://";

	@Override
	public void init() throws ServletException {
		super.init();
		try {
			client = new WebSocketClient(new URI(url), new Draft_17()) {

				@Override
				public void onOpen(ServerHandshake arg0) {
					// TODO Auto-generated method stub
					System.out.println("打开链接");

				}

				@Override
				public void onMessage(String arg0) {
					FaceSocketServer server = new FaceSocketServer();
					try {
						server.onMessage(arg0);
					} catch (IOException e) {
						e.printStackTrace();
					}

				}

				@Override
				public void onError(Exception arg0) {
					// TODO Auto-generated method stub
					arg0.printStackTrace();
					System.out.println("发生错误已关闭");

				}

				@Override
				public void onClose(int arg0, String arg1, boolean arg2) {
					// TODO Auto-generated method stub
					System.out.println("链接已关闭");

				}

				@Override
				public void onMessage(ByteBuffer bytes) {
					try {
						System.out.println(new String(bytes.array(), "utf-8"));
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
				}
			};
		} catch (URISyntaxException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		client.connect();
		client.send("hello world");

	}

}

在web.xml添加配置

其中load-on-startup标签是指该方法的执行顺序


		FaceSocketClientManage
		socket.FaceSocketClientManage
		1

websocket服务端

其中@ServerEndpoint("/ws/face")为前台接收地址

@ServerEndpoint("/ws/face")
@Component
public class FaceSocketServer {

	private Logger logger = LoggerFactory.getLogger(FaceSocketServer.class);
	private static final String SOCKET = "FaceWebSocket_";

	private Session session;

	public Session getSession() {
		return session;
	}

	public void setSession(Session session) {
		this.session = session;
	}

	@OnOpen
	public void onOpen(Session session) throws Exception {
		logger.error("@onopen   连接 ");
		this.session = session;
		FaceSocketMapUtil.put(SOCKET + session.getId(), session);
	}

	@OnClose
	public void onClose() throws Exception {
		FaceSocketMapUtil.remove(SOCKET + session.getId());
	}

	@OnMessage
	public void onMessage(String message) throws IOException {
		try {
			logger.info("websocket发送的消息:" + message);			
			this.sendMessageAll(message);
		} catch (Exception e) {
			logger.error("@OnMessage onMessage:", e.getLocalizedMessage());
		}
	}

	@OnError
	public void onError(Session session, Throwable error) {
		logger.error("@OnError OnError:", error.getLocalizedMessage());
	}

	// 对所有的连接对象发送消息
	private synchronized void sendMessageAll(String message) throws IOException {
		for (Session session : FaceSocketMapUtil.getValues()) {
			session.getBasicRemote().sendText(message);
		}
	}
}

前台访问

$(function() {
			var ws = null;
			if ('WebSocket' in window) {
				ws = new WebSocket(ws_prefix+"/ws/face");
			} else if ('MozWebSocket' in window) {
				ws = new MozWebSocket(
						ws_prefix+"/ws/face");
			} else {
				console.log("浏览器不支持WebSocket");
			}
			ws.onopen = function(e) {
				console.log("人脸识别连接成功");
			}
			ws.onclose = function(e) {
				console.log("人脸识别连接断开");
			}
			ws.onmessage = function(e) {				
				var str = e.data;
			}
		});

 

你可能感兴趣的:(websocket)