使用  WebSocket  实现简单的在线聊天

使用  WebSocket  实现简单的在线聊天
        不知道WebSocket的朋友可以去以下网址了解一下,
        我这里就不做解释了,网站上的远比我讲的要详细
        链接: 看完让你彻底搞懂Websocket原理 
        
        那废话不多说直接开始代码之旅(秃头之路)吧 !(づ ̄3 ̄)づ╭❤~

项目环境+主要框架
    idea+jdk1.8+SpringBoot+WebSocket

1.项目大致架构

考虑到有些朋友没用过SpringBoot,我这边放一下教程地址

SpringBoot入门,快速搭建简单Web应用环境
项目大致架构


2.WebSocket相关配置
这里只提供WebSocket相关的Maven配置,其他的根据自身需求,这里就不提供了,望理解

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

3.主要代码

package com.online.chat.chatting.websocket;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author shkstart
 * @create 2018-08-10 16:34
 */
@ServerEndpoint("/websocket/{name}")
@RestController
public class WebSocket {
    //存储客户端的连接对象,每个客户端连接都会产生一个连接对象
    private static ConcurrentHashMap<String,WebSocket> map=new ConcurrentHashMap();
    //每个连接都会有自己的会话
    private Session session;
    private String name;
    HttpServletRequest request;
    HttpServletResponse response;

    @OnOpen
    public void open(@PathParam("name") String name, Session session){
        map.put(name,this);
        System.out.println(name+"连接服务器成功");
        System.out.println("客户端连接个数:"+getConnetNum());

        this.session=session;
        this.name=name;

        //登入名存储Cookie
        /*Cookie userCookie=new Cookie("loginName",name);
        userCookie.setMaxAge(5*60);   //存活期为五分钟   5*60
        userCookie.setPath("/");
        response.addCookie(userCookie);*/
    }
    @OnClose
    public void close() throws IOException {
        send(name+":退出聊天!");
        map.remove(name);
        System.out.println(name+"断开了服务器连接");
    }
    @OnError
    public void error(Throwable error){
        error.printStackTrace();
        System.out.println(name+"出现了异常");
    }
    @OnMessage
    public void getMessage(String message) throws IOException {
        System.out.println("收到"+name+":"+message);
        System.out.println("客户端连接个数:"+getConnetNum());

        Set<Map.Entry<String, WebSocket>> entries = map.entrySet();
        for (Map.Entry<String, WebSocket> entry : entries) {
            if(!entry.getKey().equals(name)){//将消息转发到其他非自身客户端
                entry.getValue().send(message);

            }
        }
    }

    public void send(String message) throws IOException {
//        Cookie[] cookies = request.getCookies();
        String name=message.substring(0,message.indexOf(":"));
        for(String loginName : map.keySet()){
//            String loginName = cookie.getValue();
            if(name.equals(loginName)){ //如果该用户已登录
                if(session.isOpen()){
                    session.getBasicRemote().sendText(message);
                }
            }
        }
    }


    public int  getConnetNum(){
        return map.size();
    }
}
package com.online.chat.chatting.websocket;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /**
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     * @return
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

4.页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Chatting</title>
</head>
<style>
    #message{
        width: 50%;
        height: 500px;
        border: 1px solid black;
        background-color: darkgray;
    }

    #inputVal{
        width: 50%;
    }
    #login{
        width: 30%;
    }
    input{
        width: 92%;
    }
</style>
<body>
<h1>WebSocket聊天室</h1>
<div id="login">
<input type="text" id="uName" name="name">
<button onclick="login()">登入</button>
</div>
<div id="message">

</div>
<div id="inputVal">
    <input type="text" name="text">
    <button onclick="send()">发送</button>
</div>

<script>
    var messageEl=document.getElementById("message");
    var inputEl=document.getElementsByName("text")[0];
    var websocket=null;
    function login() {
        if('WebSocket' in window){
            websocket=new WebSocket("ws:192.168.0.115:8090/OnLineChat/websocket/"+$("#uName").val());
        }else {
            alert("浏览器不支持");

        }
        websocket.onopen=function () {
            console.log("webscoket已经连接成功");
            addMessage($("#uName").val()+"进入群聊!");

        };
        websocket.onmessage=function (event) {
            addMessage(event.data);
        };
        websocket.onclose=function () {
            console.log("webscoket连接失败");
            addMessage($("#uName").val()+"退出群聊!");
        };
        websocket.onerror=function () {
            console.log("webscoket连接失败");
            addMessage($("#uName").val()+"进入群聊失败!请重新尝试!");
        };

    }

    function addMessage(message) {
        messageEl.innerHTML+=message+"</br>";
    }

    function send() {
        websocket.send($("#uName").val()+":"+inputEl.value);
        messageEl.innerHTML+="我:"+inputEl.value+"</br>";
    }


</script>
<script type="text/javascript" src="js/jquery-3.2.1.js"></script>
</body>
</html>

5.效果

 

 

6.补充

为了测试完美,可以跟身边小伙伴分享一下地址,将  “localhost” 换成 ip地址  (ps:链接同一个WIFI)

Win+R :cmd   输入  ipconfig   回车

补充application配置

ps:代码是死的人是活的,根据自身情况修改,百度是个好东西!

同样是萌新的我第一次尝试做这个,代码比较水!

要是有大佬有更好的方法,有时间的话可以在评论区留言,供大家参考,谢谢!

大概就这也能咯,这也是本人在百度中总结出来的,希望可以帮到大家,如有雷同请见谅!!!

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值