package com.sjy.websocket;

public class Info {
	private int code;
	private String nickName;
	private String msg;
	public Info(int code, String nickName, String msg) {
		super();
		this.code = code;
		this.nickName = nickName;
		this.msg = msg;
	}
	
	
}
package com.sjy.websocket;


import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.CloseReason;
import javax.websocket.EndpointConfig;
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;

import com.google.gson.Gson;

 
/**
 * @author ccq
 * @Description webSocket服务
 * @date 2017/12/16 17:31
 */
@ServerEndpoint(value="/chatServer/{userName}")
public class ChatServer {
	private static Gson gson = new Gson();
    private static int onlineCount = 0; // 记录连接数目
    //ConcurrentHashMap是线程安全的集合容器,特别是在多线程和并发环境中
    private static CopyOnWriteArraySet<UserMsg> webSocketSet = new CopyOnWriteArraySet<UserMsg>(); //在线用户


    /**
     * 连接成功调用的方法
     */
    @OnOpen
    public void onOpen(@PathParam("userName") String userName, Session session, EndpointConfig config){
        // 增加用户数量
        addOnlineCount();
 
        // 将当前用户存到在线用户列表中
        webSocketSet.add(new UserMsg(session,userName));
        
        System.out.println("用户"+userName+"连接");
    }
 
    /**
     * 连接关闭方法
     */
    @OnClose
    public void onClose(Session session,CloseReason closeReason){
 
 
        // 减少当前用户
        subOnlienCount();
 
 
    }
 
    /**
     * 接收客户端的message,判断是否有接收人而选择进行广播还是指定发送
     * @param data 客户端发来的消息
     */
    @OnMessage
    public void onMessage(@PathParam("userName") String userName,String data,Session session){
    	System.out.println(userName+"收到信息"+data);
    	//群发消息
        for(UserMsg um: webSocketSet){
            try {
            	Session uSession = um.getSession();
            	if(!uSession.equals(session)){
            		sendMsg(uSession, new Info(1,userName,data));
            	}
            } catch (IOException e) {
                e.printStackTrace();
                continue;
            }
        }
    }
 
    /**
     * 发生错误
     * @param throwable
     */
    @OnError
    public void onError(Session session,Throwable throwable){
    	throwable.printStackTrace();
    }
 
 
    public static int getOnlineCount() {
        return onlineCount;
    }
    public synchronized void addOnlineCount(){
        onlineCount++;
    }
    public synchronized void subOnlienCount(){
        onlineCount--;
    }
    
    public static void sendMsg(Session session,Info info) throws IOException{
    	session.getBasicRemote().sendText(gson.toJson(info));
    }
}

 

package com.sjy.websocket;

import javax.websocket.Session;

public class UserMsg {
	private Session session;
	private String nickName;
	
	
	
	public UserMsg(Session session, String nickName) {
		super();
		this.session = session;
		this.nickName = nickName;
	}
	public Session getSession() {
		return session;
	}
	public void setSession(Session session) {
		this.session = session;
	}
	public String getNickName() {
		return nickName;
	}
	public void setNickName(String nickName) {
		this.nickName = nickName;
	}
	
	
}

 

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
	.message{
		width:900px;
		height:400px;
		background-color:pink;
	}
</style>
</head>
<body>
	昵称:<input type="text" id="nickname">
	<button onclick="connect()">连接</button>
	<div id="message" class="message"></div>
	<br>
	发送消息:<input type="text" id="msg">
	<button onclick="send()">发送</button>
</body>
<script type="text/javascript">
//打开一个 web socket
var websocket = null;

//连接
function connect(){
	//获取昵称
	var nickname = document.getElementById('nickname').value;
	
	//判断当前浏览器是否支持WebSocket
	if ('WebSocket' in window) {
		websocket = new WebSocket("ws://"+document.location.host+"/WebSocket/chatServer/"+nickname);
	}else {
	    alert('当前浏览器不支持WebSocket')
	}


	//连接发生错误的回调方法 
	websocket.onerror = function() { 
	 setMessageInnerHTML("WebSocket连接发生错误"); 
	}; 
	//连接成功建立的回调方法 
	websocket.onopen = function() { 
	 setMessageInnerHTML("WebSocket连接成功"); 
	} 
	//接收到消息的回调方法 
	websocket.onmessage = function(event) {
		//str转json字符串
		var data = JSON.parse(event.data);
		if(data.code == 1){
			var umsg = data.nickName + "说:";
			umsg += data.msg;
			setMessageInnerHTML(umsg);
		}
	 
	} 
	//连接关闭的回调方法 
	websocket.onclose = function() { 
	 setMessageInnerHTML("WebSocket连接关闭"); 
	} 
	
}
//将消息显示在网页上
function setMessageInnerHTML(innerHTML) {
    document.getElementById('message').innerHTML += innerHTML + '<br/>';
}

function send(){
	//发送信息
	var message = document.getElementById('msg').value;
	websocket.send(message);
}


</script>
</html>

 

最后修改于 2021-03-30 22:32:36
如果觉得我的文章对你有用,请随意赞赏
扫一扫支付
上一篇