java代码:
package com.lpc.main;
import java.io.IOException;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
/**
* * 类名称:Server.java 类描述:简单的聊天室 作 者:wantao 时 间:2018年03月08日 23:11:48
*/
@ServerEndpoint(value = "/chat")
public class Test {
private static final String GUEST_PREFIX = "用户";
/**
* 一个提供原子操作的Integer的类。在Java语言中,++i和i++操作并不是线程安全的,
* 在使用的时候,不可避免的会用到synchronized关键字。 而AtomicInteger则通过一种线程安全的加减操作接口。
*/
private static final AtomicInteger connectionIds = new AtomicInteger(0);
// 存放用户的websocket
private static final Set<Test> connections = new CopyOnWriteArraySet<>();
private final String nickname;
private Session session;
public Test() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
}
/**
* 创建连接时间调用的方法
*
* @param session
*/
@OnOpen
public void start(Session session) {
this.session = session;
connections.add(this);
String message = String.format("* %s %s", nickname, "加入聊天室");
// 上线通知
broadcast(message);
try {
// 系统问候语
SendHello(this.nickname);
// 返回在线用户
onlineList();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 链接关闭时调用方法
*/
@OnClose
public void end() {
connections.remove(this);
String message = String.format("* %s %s", nickname, "退出聊天室");
broadcast(message);
}
/**
* 传输信息过程中调用方法
*
* @param message
*/
@OnMessage
public void incoming(String message) {
// Never trust the client
// TODO: 过滤输入的内容
String m = String.format("* %s %s", nickname, message);
if (m.contains("to")) {
// 点对点发送
broadcastOneToOne(m, nickname);
} else {
// 群发
broadcast(m);
}
}
/**
* 发生错误是调用方法
*
* @param t
* @throws Throwable
*/
@OnError
public void onError(Throwable t) throws Throwable {
System.out.println("错误: " + t.toString());
}
/**
* 消息广播 通过connections,对所有其他用户推送信息的方法
*
* @param msg
*/
private static void broadcast(String msg) {
for (Test client : connections) {
try {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
}
} catch (IOException e) {
System.out.println("错误:向客户端发送消息失败");
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String message = String.format("* %s %s", client.nickname,
"退出聊天室");
broadcast(message);
}
}
}
/**
* 点对点发送消息 通过connections,对所有其他用户推送信息的方法
*
* @param msg
*/
private static void broadcastOneToOne(String msg, String nickName) {
String[] arr = msg.split("to");
for (Test client : connections) {
try {
if (arr[1].equals(client.nickname)
|| nickName.equals(client.nickname)) {
synchronized (client) {
client.session.getBasicRemote().sendText(arr[0]);
}
}
} catch (IOException e) {
System.out.println("错误:向客户端发送消息失败");
connections.remove(client);
try {
client.session.close();
} catch (IOException e1) {
e1.printStackTrace();
}
String message = String.format("* %s %s", client.nickname,
"退出聊天室");
broadcast(message);
}
}
}
// 系统问候语
private static void SendHello(String nickName) throws IOException {
String m = String.format("* %s %s", nickName, "你好");
for (Test client : connections) {
if (client.nickname.equals(nickName)) {
client.session.getBasicRemote().sendText(m);
}
}
}
// 在线用户
private static void onlineList() throws IOException {
String online = "";
for (Test client : connections) {
if (online.equals("")) {
online = client.nickname;
} else {
online += "," + client.nickname;
}
}
String m = String.format("* %s %s", "当前在线用户", online);
for (Test client : connections) {
client.session.getBasicRemote().sendText(m);
}
}
}
jsp文件
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>websocket</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
input#chat {
width: 410px
}
#console-container {
width: 400px;
}
#console {
border: 1px solid #CCCCCC;
border-right-color: #999999;
border-bottom-color: #999999;
height: 170px;
overflow-y: scroll;
padding: 5px;
width: 100%;
}
#console p {
padding: 0;
margin: 0;
}
</style>
<script type="application/javascript">
"use strict";
var Chat = {};
Chat.socket = null;
Chat.connect = (function(host) {
if ('WebSocket' in window) {
Chat.socket = new WebSocket(host);
} else if ('MozWebSocket' in window) {
Chat.socket = new MozWebSocket(host);
} else {
Console.log('Error: 浏览器不支持WebSocket');
return;
}
Chat.socket.onopen = function () {
Console.log('Info: WebSocket链接已打开');
document.getElementById('chat').onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
}
};
};
Chat.socket.onclose = function () {
document.getElementById('chat').onkeydown = null;
Console.log('Info: webcocket关闭.');
};
Chat.socket.onmessage = function (message) {
Console.log(message.data);
};
});
Chat.initialize = function() {
if (window.location.protocol == 'http:') {
Chat.connect('ws://' + window.location.host + '/WebSocket/chat');
} else {
Chat.connect('wss://' + window.location.host + '/WebSocket/chat');
}
};
Chat.sendMessage = (function() {
var message = document.getElementById('chat').value;
if (message != '') {
Chat.socket.send(message);
document.getElementById('chat').value = '';
}
});
var Console = {};
Console.log = (function(message) {
var console = document.getElementById('console');
var p = document.createElement('p');
p.style.wordWrap = 'break-word';
p.innerHTML = message;
console.appendChild(p);
while (console.childNodes.length > 25) {
console.removeChild(console.firstChild);
}
console.scrollTop = console.scrollHeight;
});
Chat.initialize();
document.addEventListener("DOMContentLoaded", function() {
// Remove elements with "noscript" class - <noscript> is not allowed in XHTML
var noscripts = document.getElementsByClassName("noscript");
for (var i = 0; i < noscripts.length; i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}
}, false);
</script>
</head>
<body>
<div class="noscript"><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websockets rely on Javascript being enabled. Please enable
Javascript and reload this page!</h2></div>
<div>
<p>
<input type="text" placeholder="输入文字,回车发送" id="chat" /><br>
注意:输入 消息to用户名 发送给指定用户 比如: 你好to用户1<br>
输入 消息 直接发送给全体用户
</p>
<div id="console-container">
<div id="console"/>
</div>
</div>
</body>
</html>
运行后提示
Info: webcocket关闭.
eclipse控制台输出信息:
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server.服务器版本: Apache Tomcat/9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server.构建: Mar 13 2019 15:55:27 UTC
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Server version number: 9.0.17.0
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS Name: Windows 10
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: OS.版本: 10.0
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: 结.造: amd64
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Java 环境变量: C:\Program Files\Java\jdk-11.0.2
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM 版本: 11.0.2+9-LTS
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: JVM.供应商: Oracle Corporation
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_BASE: D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: CATALINA_HOME: D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.base=D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dcatalina.home=D:\workspace\eclipse-web\apache-tomcat-9.0.17
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dwtp.deploy=D:\workspace\eclipse-web\apache-tomcat-9.0.17\wtpwebapps
4月 15, 2019 9:30:31 下午 org.apache.catalina.startup.VersionLoggerListener log
信息: Command line argument: -Dfile.encoding=GBK
4月 15, 2019 9:30:31 下午 org.apache.catalina.core.AprLifecycleListener lifecycleEvent
信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk-11.0.2\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jdk-11.0.2/bin/server;C:/Program Files/Java/jdk-11.0.2/bin;C:\Program Files\Java\jdk-11.0.2\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\System32\OpenSSH\;C:\Program Files\dotnet\;C:\Program Files\MySQL\MySQL Server 8.0\bin;C:\Program Files\MATLAB\R2016a\runtime\win64;C:\Program Files\MATLAB\R2016a\bin;C:\Program Files\MATLAB\R2016a\polyspace\bin;C:\Program Files\Git\cmd;C:\Program Files\apache-maven-3.6.0\bin;C:\MinGW\bin;C:\Users\xupt1602\AppData\Local\Microsoft\WindowsApps;C:\Users\xupt1602\.dotnet\tools;C:\Users\xupt1602\AppData\Local\GitHubDesktop\bin;;C:\WINDOWS\system32;;.]
4月 15, 2019 9:30:31 下午 org.apache.coyote.AbstractProtocol init
信息: 初始化协议处理器 ["http-nio-8080"]
4月 15, 2019 9:30:32 下午 org.apache.coyote.AbstractProtocol init
信息: 初始化协议处理器 ["ajp-nio-8009"]
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.Catalina load
信息: 服务器在[2,091]毫秒内初始化
4月 15, 2019 9:30:32 下午 org.apache.catalina.core.StandardService startInternal
信息: Starting service [Catalina]
4月 15, 2019 9:30:32 下午 org.apache.catalina.core.StandardEngine startInternal
信息: Starting Servlet engine: [Apache Tomcat/9.0.17]
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deploying deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml]
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.HostConfig deployDescriptor
警告: The path attribute with value [/TocmatTest] in deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml] has been ignored
4月 15, 2019 9:30:32 下午 org.apache.catalina.startup.HostConfig deployDescriptor
警告: Deployment of deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml] with an external docBase means the directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\TocmatTest] in the appBase will be ignored
4月 15, 2019 9:30:33 下午 org.apache.catalina.util.SessionIdGeneratorBase createSecureRandom
警告: Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [528] milliseconds.
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDescriptor
信息: Deployment of deployment descriptor [D:\workspace\eclipse-web\apache-tomcat-9.0.17\conf\Catalina\localhost\TocmatTest.xml] has finished in [1,258] ms
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 应用程序部署到目录 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\docs]
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\docs] has finished in [66] ms
4月 15, 2019 9:30:33 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 应用程序部署到目录 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\examples]
4月 15, 2019 9:30:34 下午 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: contextInitialized()
4月 15, 2019 9:30:34 下午 org.apache.catalina.core.ApplicationContext log
信息: SessionListener: contextInitialized()
4月 15, 2019 9:30:34 下午 org.apache.catalina.core.ApplicationContext log
信息: ContextListener: attributeAdded('StockTicker', 'async.Stockticker@437e951d')
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\examples] has finished in [660] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 应用程序部署到目录 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\host-manager]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\host-manager] has finished in [59] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 应用程序部署到目录 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\manager]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\manager] has finished in [104] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 应用程序部署到目录 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\ROOT]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\ROOT] has finished in [57] ms
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: 把web 应用程序部署到目录 [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\WebContent]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.HostConfig deployDirectory
信息: Deployment of web application directory [D:\workspace\eclipse-web\apache-tomcat-9.0.17\webapps\WebContent] has finished in [58] ms
4月 15, 2019 9:30:34 下午 org.apache.coyote.AbstractProtocol start
信息: 开始协议处理句柄["http-nio-8080"]
4月 15, 2019 9:30:34 下午 org.apache.coyote.AbstractProtocol start
信息: 开始协议处理句柄["ajp-nio-8009"]
4月 15, 2019 9:30:34 下午 org.apache.catalina.startup.Catalina start
信息: Server startup in [2,502] milliseconds
4月 15, 2019 9:49:16 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/TocmatTest] has started
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.apache.catalina.loader.WebappClassLoaderBase (file:/D:/workspace/eclipse-web/apache-tomcat-9.0.17/lib/catalina.jar) to field java.io.ObjectStreamClass$Caches.localDescs
WARNING: Please consider reporting this to the maintainers of org.apache.catalina.loader.WebappClassLoaderBase
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
4月 15, 2019 9:49:17 下午 org.apache.catalina.core.StandardContext reload
信息: Reloading Context with name [/TocmatTest] is completed