首页 > 编程语言 >基于Java websocket的公共聊天程序

基于Java websocket的公共聊天程序

时间:2022-10-27 13:35:29浏览次数:46  
标签:username info Java WebSocket 聊天 import websocket ws


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

相关描述

Java工程项目结构如下(eclipse):

基于Java websocket的公共聊天程序_java

代码

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

效果

基于Java websocket的公共聊天程序_java_02


标签:username,info,Java,WebSocket,聊天,import,websocket,ws
From: https://blog.51cto.com/u_15847885/5800890

相关文章