java websocket实现即时聊天系统

即时聊天系统

后台代码

package com.wyn.pro.wynpro.customermanager.test;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;

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 net.sf.json.JSONObject;

@ServerEndpoint("/hello/{username}")
public class WebsocketTest {
    private Session session;
    private String username;

    //静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。  
    private static int onlineCount = 0;

    private static final CopyOnWriteArraySet<WebsocketTest> webSocketSet=new CopyOnWriteArraySet<WebsocketTest>();

    // 日期格式化  
    private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    public WebsocketTest(){
        System.out.println("WebsocketTest..");
    }

    @OnOpen
    public void onopen(Session session,@PathParam("username") String username){
        System.out.println("连接成功");
        this.session=session;
        this.username=username;
        webSocketSet.add(this);
        addOnlineCount();
        System.out.println(onlineCount);
    }

    /**  
     * 接受客户端的消息,并把消息发送给所有连接的会话  
     * @param message 客户端发来的消息  
     * @param session 客户端的会话  
     */    
    @OnMessage      
    public void onsend(Session session,String msg){
        try {
            JSONObject fObject = JSONObject.fromObject(msg);
            fObject.put("date", DATE_FORMAT.format(new Date()));
            for(WebsocketTest websocketTest:webSocketSet) {
                synchronized (WebsocketTest.class) { 
                    fObject.put("isSelf", websocketTest.session.equals(session));
                    fObject.put("username", this.username);
                    fObject.put("num", onlineCount);
                    //websocketTest.session.getAsyncRemote().sendText(fObject.toString());
                    websocketTest.sendMessage(fObject.toString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onclose(Session session){
        // 添加关闭会话时的操作  
        webSocketSet.remove(this);  //从set中删除  
        subOnlineCount();           //在线数减1  
        System.out.println("close....");
    }

    @OnError   
    public void error(Throwable t) {    
        // 添加处理错误的操作    
        System.out.println("发生错误了");  
    }  

    public  static synchronized void addOnlineCount() {
        WebsocketTest.onlineCount++;
    }

    public static synchronized void subOnlineCount() {  
        WebsocketTest.onlineCount--;  
    }  

    public synchronized  void  sendMessage(String message) throws IOException{  
        this.session.getAsyncRemote().sendText(message);//非阻塞式的  
    }  

}

前台页面代码

<%@ 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>即时聊天系统</title>
</head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
    var websocket;

    function linksys(){
        //debugger
        if(websocket){
            alert("已经建立连接");
            return;
        }
        var username = $("#name").val();
        if(username==null||username==""){
            alert("请先输入代号");
            return;
        }
        websocket = new WebSocket("ws://192.168.0.17:9999/order/hello/"+username);
        /*与后台系统建立连接  */
        websocket.onopen = function(evn){
            console.log("与后台系统建立连接---------当前连接数:");
        }

        websocket.onmessage = function(evn){
            debugger
            message = JSON.parse(evn.data);
            $("#num").text(message.num);
            //alert(message.username);
            $("#table").append("<tr><td>"+message.username+"</td><td>"+message.date+"</td></tr><tr><td colspan='2'>"+message.content+"</td></tr>");
        } 

        websocket.onclose = function(){
                console.log("关闭");
         };
    }

    function subsend(){
        if(websocket){
            content1 = $("#content").val();
            jsonstr=JSON.stringify({  
                content : content1 
            });
            //alert(jsonstr);
            websocket.send(jsonstr);
        }else{
            alert("请先连接,再发送信息");
        }
    }

</script>
<body>
<h1>即时聊天系统</h1>
当前用户姓名<input type="text" name="username" id="name"><button onclick="linksys()">连接系统</button><br>
聊天内容<input type="text" name="content" id="content"><button onclick="subsend()" >发送</button><br>
当前在线客户<p id="num"><p>
---------------------------------------------------------------<br>
聊天记录<br>
<table id="table" border="1">
</table>
</body>
</html>

maven依赖

<!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
    <dependency>
        <groupId>commons-beanutils</groupId>
        <artifactId>commons-beanutils</artifactId>
        <version>1.8.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
    <dependency>
        <groupId>commons-collections</groupId>
        <artifactId>commons-collections</artifactId>
        <version>3.2.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
    <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.5</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.sf.ezmorph/ezmorph -->
    <dependency>
        <groupId>net.sf.ezmorph</groupId>
        <artifactId>ezmorph</artifactId>
        <version>1.0.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
        <classifier>jdk15</classifier>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.websocket/javax.websocket-api -->
    <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.0</version>
        <scope>provided</scope>
    </dependency>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章