tomcat8 实现websocket demo

版权声明:本人承诺所发文章均为亲测可用,可在学习交流群616698275(答案easy),提出各自疑问。 https://blog.csdn.net/zml_moxueli/article/details/84827468

代码实现:

引用:

<dependency>
         <groupId>javax</groupId>
         <artifactId>javaee-api</artifactId>
         <version>8.0</version>
         <scope>provided</scope>
 </dependency>

实现:

package com.xjcy.test.controller;


import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.websocket.MessageHandler;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;  
import javax.websocket.server.ServerEndpoint;  

@ServerEndpoint("/websocket/{username}")  
public class SocketTest {  
  
    private static int onlineCount = 0;  
    private static Map<String, SocketTest> clients = new ConcurrentHashMap<>();  
    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 {  
  
    	sendMessageAll(this.username +" say:"+ message);
        //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 (SocketTest item : clients.values()) {  
            if (item.username.equals(To) )  
                item.session.getAsyncRemote().sendText(message);  
        }  
    }  
      
    public void sendMessageAll(String message) throws IOException {  
        for (SocketTest item : clients.values()) {  
            item.session.getAsyncRemote().sendText(message);  
        }  
    }  
      
      
  
    public static synchronized int getOnlineCount() {  
        return onlineCount;  
    }  
  
    public static synchronized void addOnlineCount() {  
    	SocketTest.onlineCount++;  
    }  
  
    public static synchronized void subOnlineCount() {  
    	SocketTest.onlineCount--;  
    }  
  
    public static synchronized Map<String, SocketTest> getClients() {  
        return clients;  
    }  
}  

页面实现:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
	<input type="text" id="msg" style="width: 200px;" />
	<input type="button" value="发送" onclick="send()" />
	<input type="button" value="重新连接" onclick="re()" />
	<br />
	<br />
	<textarea cols="80" rows="100" id="content"></textarea>
	<script type="text/javascript">
		var websocket = null;
		var username = new Date().getTime();
		localStorage["user"] = username;
		
		openWebSocket();

		function openWebSocket() {

			//判断当前浏览器是否支持WebSocket  
			if ('WebSocket' in window) {
				websocket = new WebSocket("ws://" + document.location.host
						+ "/test/websocket/" + username);
				//连接发生错误的回调方法  
				websocket.onerror = function() {
					setMessageInnerHTML("WebSocket连接发生错误");
				};

				//连接成功建立的回调方法  
				websocket.onopen = function() {
					setMessageInnerHTML(localStorage["user"] + "连接成功");
				}

				//接收到消息的回调方法  
				websocket.onmessage = function(event) {
					setMessageInnerHTML(event.data);
				}

				//连接关闭的回调方法  
				websocket.onclose = function() {
					setMessageInnerHTML(localStorage["user"] + "连接关闭");
				}
			} else {
				alert('当前浏览器 Not support websocket')
			}
		}

		//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。  
		window.onbeforeunload = function() {
			closeWebSocket();
		}

		//关闭WebSocket连接  
		function closeWebSocket() {
			websocket.close();
		}

		function re() {
			closeWebSocket();
			websocket = null;
			openWebSocket();
		}

		var input = document.getElementById('content');
		var text = document.getElementById('msg');

		function setMessageInnerHTML(msg) {
			if (input.value != '')
				input.value = input.value + '\r\n' + msg;
			else
				input.value = msg;
		}

		function send() {
			websocket.send(text.value);
		}
	</script>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/zml_moxueli/article/details/84827468