websocket实时通信

pom

 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

后端

@Component
@ServerEndpoint("/chat/{userId}")
public class ChatWebSocket {

    /*
    * 存储所有的在线人员信息
    * */

    private static ConcurrentHashMap<String,Session> cacheUser=new ConcurrentHashMap<>();

    /**
     *
     * @param session 通道
     * @param userId
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        System.out.println("userId:"+userId+"上线了");
        cacheUser.put(userId,session);
    }
    @OnMessage
    public void onMessage(String message,Session session)throws Exception{
        System.out.println("发送的消息"+message);
        //根据指定的规则,拆分消息,获取消息发送给谁
        String [] split=message.split(":",2);
        Assert.state(split.length==2,"接受到的消息不合法");
        //获取发送消息的人和消息
        String toUser=split[0];
        String msg=split[1];
        //根据touser,查找指定的人的通道
        Session to=cacheUser.get(toUser);
        //如果找不到,那么给发送消息的人提示对方不在线
        if(to==null){
            session.getBasicRemote().sendText("对方不在线");
            return;
        }
        //获取当前登录的账号用户
        String userId=session.getPathParameters().get("userId");
        //如果对方在线,将消息转发给对方
        to.getBasicRemote().sendText(userId+":"+msg);
        System.out.println("消息已经转发");
    }
    @OnClose
    public void onClose(Session session){
        String userId=session.getPathParameters().get("userId");
        System.out.println(userId+"下线了");
        cacheUser.remove(userId);
    }
}

@Configuration
@EnableWebSocket
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

前端

客户端1
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
		
	</head>
	<body>
		<textarea id="msg"></textarea>
	</body>
	<script>
		$(function(){
			/* $.ajax({
				url:"http://localhost:8082/demo/user/put"
			}).then(res=>{
				console.log(res)
			}) */
			let ws=new WebSocket("ws://localhost:85/chat/lisi");
			$("#msg").on("keydown",function(event){
				if(event.keyCode==13){
					event.preventDefault();
					let message=this.value;
					if(message!==""){
						//将消息发送给服务器
						ws.send(`zhangsan:${message}`)
						this.value="";
					}
				}
			})
			//接受服务器的消息
			ws.onmessage=function(event){
				console.log(event.data)
			}
		})
	</script>
</html>

客户端2
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
		
	</head>
	<body>
		<textarea id="msg"></textarea>
	</body>
	<script>
		$(function(){
			/* $.ajax({
				url:"http://localhost:8082/demo/user/put"
			}).then(res=>{
				console.log(res)
			}) */
			let ws=new WebSocket("ws://localhost:85/chat/lisi");
			$("#msg").on("keydown",function(event){
				if(event.keyCode==13){
					event.preventDefault();
					let message=this.value;
					if(message!==""){
						//将消息发送给服务器
						ws.send(`zhangsan:${message}`)
						this.value="";
					}
				}
			})
			//接受服务器的消息
			ws.onmessage=function(event){
				console.log(event.data)
			}
		})
	</script>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值