天天看點

基于Java websocket的公共聊天程式

實驗中使用的是tomcat的websocket,由于程式部署到apache-tomcat-8.5.24上,是以隻需額外添加消息Json解析包:json-org。實際使用中注意修改目标位址:ws://localhost:8080/GameDemo/websocket/,并做相關修改可實作單使用者之間的聊天。

相關描述

Java工程項目結構如下(eclipse):

基于Java websocket的公共聊天程式

代碼

/GameDemo/src/cug/lsh/dispatch/WebSocket.java

package cug.lsh.dispatch;

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

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 org.json.JSONArray;
import org.json.JSONException;

//添加注釋  
@ServerEndpoint("/websocket/{username}")
public class WebSocket

    private static int onlineCount = 0;
    private static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
    private Session session;
    private String username;

    @OnOpen
    public void onOpen(@PathParam("username") String username, Session session) throws IOException {

        this.username = username;
        this.session = session;

        WebSocket.onlineCount++;
        clients.put(username, this);
        System.out.println(username + ":已連接配接");
    }

    @OnClose
    public void onClose() throws IOException {
        clients.remove(username);
        WebSocket.onlineCount--;
    }

    @OnMessage
    public void onMessage(String message) throws IOException, JSONException {
        System.out.println("info:" + message);
        for (WebSocket item : clients.values()) {
            JSONArray jsonArray = new JSONArray();
            jsonArray.put(username);
            jsonArray.put(message);
            item.session.getAsyncRemote().sendText(jsonArray.toString());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

}      
<%@ 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>
<body>
    公共平台:
    <div id="show">
        <ol>
        </ol>
    </div>


    使用者名:
    <input type="text" id="name" value="未知使用者">
    輸入消息:
    <input type="text" id="info">

    <input type="button" value="送出" id="sub">


    <script type="text/javascript" src="js/jquery-3.0.0.min.js"></script>
    <script type="text/javascript">var ws = null;
        var target = "ws://localhost:8080/GameDemo/websocket/"
                + $("#name").val();
        if ('WebSocket' in window) {
            ws = new WebSocket(target);
        } else if ('MozWebSocket' in window) {
            ws = new MozWebSocket(target);
        } else {
            alert('WebSocket is not supported by this browser.');
        }

        ws.onopen = function(obj)
            console.info('open');
            console.info(obj);
        };

        ws.onclose = function(obj)
            console.info('close');
            console.info(obj);
        };
        ws.onmessage = function(obj)
            console.info(obj);
            $("ol").append("<li>" + obj.data + "</li>");
        };
        function q(msg)</script>
    <script type="text/javascript">"#sub").click(function()
            var r = $("#info").val();
            $("#info").val("");
            q(r);
        })
    </script>
</body>
</html>      

效果