基于Java websocket的公共聊天程序

实验中使用的是tomcat的websocket,由于程序部署到apache-tomcat-8.5.24上,所以只需额外添加消息Json解析包:json-org。实际使用中注意修改目标地址:ws://localhost:8080/GameDemo/websocket/,并做相关修改可实现单用户之间的聊天。

相关描述

Java工程项目结构如下(eclipse):
这里写图片描述

代码

/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();
    }

}

/GameDemo/WebContent/persion.jsp

<%@ 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) {
            ws.send(msg);
        }
    </script>
    <script type="text/javascript">
        $("#sub").click(function() {
            var r = $("#info").val();
            $("#info").val("");
            q(r);
        })
    </script>
</body>
</html>

效果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值