基于webscoket的聊天室怎么javaweb实现聊天室私聊的

使用WebSocket实现网页聊天室
时间: 17:12:39
&&&& 阅读:362
&&&& 评论:
&&&& 收藏:0
标签: 知道WebSocket挺久了,但是一直没提起兴趣去了解它。
今天听 说到。小小的试用了一下,发现slack的聊天功能做得相当强大,看了下网络请求,发现是基于WebSocket实现的。顿时提起兴趣,想了解下这强大的WebSocket。
先了解下WebSocket。
开源中国的介绍:
百度百科的介绍:
网上关于WebSocket的例子貌似不多,但最好的例子已经有了。偶然间发现tomcat的自带的例子中,已经有了基于WebSocket实现的聊天室例子。这里就不献丑,直接拿来用了。
首先,服务端的实现ChatAnnotation.java
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.
See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
package websocket.
import java.io.IOE
import java.util.S
import java.util.concurrent.CopyOnWriteArrayS
import java.util.concurrent.atomic.AtomicI
import javax.websocket.OnC
import javax.websocket.OnE
import javax.websocket.OnM
import javax.websocket.OnO
import javax.websocket.S
import javax.websocket.server.ServerE
@ServerEndpoint(value = "/chat")
public class ChatAnnotation {
private static final String GUEST_PREFIX = "Guest";
private static final AtomicInteger connectionIds = new AtomicInteger(0);
private static final Set&ChatAnnotation& connections =
new CopyOnWriteArraySet&&();
private final S
public ChatAnnotation() {
nickname = GUEST_PREFIX + connectionIds.getAndIncrement();
public void start(Session session) {
this.session =
connections.add(this);
String message = String.format("* %s %s", nickname, "has joined.");
broadcast(message);
public void end() {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
@OnMessage
public void incoming(String message) {
// Never trust the client
// TODO: 过滤输入的内容
broadcast(message);
public void onError(Throwable t) throws Throwable {
System.out.println("Chat Error: " + t.toString());
private static void broadcast(String msg) {
for (ChatAnnotation client : connections) {
synchronized (client) {
client.session.getBasicRemote().sendText(msg);
} catch (IOException e) {
System.out.println("Chat Error: Failed to send message to client");
connections.remove(client);
client.session.close();
} catch (IOException e1) {
String message = String.format("* %s %s",
client.nickname, "has been disconnected.");
broadcast(message);
稍微解释下上面这段代码。
@ServerEndpoint(value = "/websocket/chat")定义一个WebSocket服务端。value即访问地址。这个例子中:客户端通过 ws://{domain}/{context}/chat 来进行连接
Set&ChatAnnotation& connections用于存储聊天室中的连接实例
@OnPen,连接创建时调用的方法
@OnClose,连接关闭时调用的方法
@OnMessage,传输信息过程中调用的方法
@OnError,发生错误时调用的方法
broadcast(String msg),通过connections,对所有其他用户推送信息的方法
客户端的实现chat.xhtml
&?xml version="1.0" encoding="UTF-8"?&
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements.
See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
&html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&
&title&Apache Tomcat WebSocket Examples: Chat&/title&
&style type="text/css"&&![CDATA[
input#chat {
width: 410px
#console-container {
width: 400
#console {
border: 1px solid #CCCCCC;
border-right-color: #999999;
border-bottom-color: #999999;
height: 170
overflow-y:
padding: 5
width: 100%;
#console p {
padding: 0;
margin: 0;
]]&&/style&
&script type="application/javascript"&&![CDATA[
"use strict";
var Chat = {};
Chat.socket =
Chat.connect = (function(host) {
if (‘WebSocket‘ in window) {
Chat.socket = new WebSocket(host);
} else if (‘MozWebSocket‘ in window) {
Chat.socket = new MozWebSocket(host);
Console.log(‘Error: WebSocket is not supported by this browser.‘);
Chat.socket.onopen = function () {
Console.log(‘Info: WebSocket connection opened.‘);
document.getElementById(‘chat‘).onkeydown = function(event) {
if (event.keyCode == 13) {
Chat.sendMessage();
Chat.socket.onclose = function () {
document.getElementById(‘chat‘).onkeydown =
Console.log(‘Info: WebSocket closed.‘);
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‘);
Chat.connect(‘wss://‘ + window.location.host + ‘/websocket/chat‘);
Chat.sendMessage = (function() {
var message = document.getElementById(‘chat‘).
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 =
console.appendChild(p);
while (console.childNodes.length & 25) {
console.removeChild(console.firstChild);
console.scrollTop = console.scrollH
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. i++) {
noscripts[i].parentNode.removeChild(noscripts[i]);
}, false);
]]&&/script&
&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&
&input type="text" placeholder="type and press enter to chat" id="chat" /&
&div id="console-container"&
&div id="console"/&
客户端的代码也是很简单,就是载入页面的时候,创建跟服务器的WebSocket连接。
Chat.connect(‘ws://‘ + window.location.host + ‘/websocket/chat‘);
然后就是发送信息,接收信息了。
完成上述代码之后,就可以部署了。这里我使用的servlet容器是tomcat 8。以下是我的配置:
&Context path="/websocket" docBase="/Users/cevin/Documents/workspace/tomcat_websocket_chat/web" reloadable="true"/&
部署结束,启动tomcat,访问:http://localhost:8080/websocket/chat.xhtml,见到下面这个页面,说明部署成功了。
基本上,通过这个例子就可以知道如何使用WebSocket来进行开发了。这么强大的WebSocket,想一想都觉得兴奋! 标签:
&&国之画&&&& &&
版权所有 京ICP备号-2
迷上了代码!简单的websocket聊天室demo - CNode技术社区
这家伙很懒,什么个性签名都没有留下。
最近在学习 websocket ,选择了ws 这个库,做了一个简单的聊天室demo,使用 Express 3 框架。
npm install
node app.js
代码托管在github上,
项目参考了国外的,不同的是老外用的是WebSocket-Node。
views/chat.html
能放出来?
用的sendfile,可以
为啥很不稳定了 ?需要另外对连接进行维护么?
这只是一个简单的小例子,帮助大家熟悉下websocket
CNode 社区为国内最专业的 Node.js 开源技术社区,致力于 Node.js 的技术研究。
服务器赞助商为
,存储赞助商为
,由提供应用性能服务。
新手搭建 Node.js 服务器,推荐使用无需备案的websocket 在线聊天室,实现实时用户间的登陆 功能,利用 Win -NDIS 网络编程 256万源代码下载-
&文件名称: websocket& & [
& & & & &&]
&&所属分类:
&&开发工具: Java
&&文件大小: 13 KB
&&上传时间:
&&下载次数: 32
&&提 供 者:
&详细说明:在线聊天室,实现实时用户间的登陆聊天功能,利用websocket-Online chat rooms
文件列表(点击判断是否您需要的文件,如果是垃圾请在下面评价投诉):
&&websocket&&.........\.classpath&&.........\.project&&.........\.settings&&.........\.........\.jsdtscope&&.........\.........\org.eclipse.jdt.core.prefs&&.........\.........\org.eclipse.wst.jsdt.ui.superType.container&&.........\.........\org.eclipse.wst.jsdt.ui.superType.name&&.........\build&&.........\.....\classes&&.........\.....\.......\com&&.........\.....\.......\...\bs&&.........\.....\.......\...\..\websocket&&.........\.....\.......\...\..\.........\servlet&&.........\.....\.......\...\..\.........\.......\WsChatServlet$EchoMessageInbound.class&&.........\.....\.......\...\..\.........\.......\WsChatServlet.class&&.........\src&&.........\...\com&&.........\...\...\bs&&.........\...\...\..\websocket&&.........\...\...\..\.........\servlet&&.........\...\...\..\.........\.......\WsChatServlet.java&&.........\WebContent&&.........\..........\lisi.html&&.........\..........\META-INF&&.........\..........\........\MANIFEST.MF&&.........\..........\WEB-INF&&.........\..........\.......\lib&&.........\..........\.......\web.xml&&.........\..........\zhangsan.html
&[]:纯粹是垃圾
&近期下载过的用户:
&相关搜索:
&输入关键字,在本站256万海量源码库中尽情搜索:
&[] - html5 案例源代码 WebSocket
&[] - 模拟实现存储管理器和缓冲存储器,数据库系统实现实验的源码
&[] - 通过WebSocket简单实现多人聊天系统,可以把源程序部分放在tomcat里,打开html网页,可实现,是html5新功能实现的网络编程
&[] - WebSocket简单聊天室websocket简单聊天室
&[] - web在线聊天,WebSocket机制,代码清晰
&[] - jWebSocket Clients C 纯JavaScript的WebSocket客户端,多个子协议和可选的用户、session、timeout管理机制。无需插件。并且现在可以应用在任何其他Java、Android客户端。
&[] - 使用java编写的网络套接字封装类,可以直接在程序中调用,功能比较基础。不多说了,直接看……index.jsp&%@ page language=&& contentType=&text/ charset=UTF-8& pageEncoding=&UTF-8&%&&html&&head&&meta http-equiv=&Content-Type& content=&text/ charset=UTF-8&&&title&websocket聊天室&/title&&style type=&text/css&&
text-align:
width: 600
height: 500 } #up{
text-align:
width: 100%;
height: 400 } #down{
text-align:
height: 100
width: 100%; }&/style&&/head&&body&&h2 align=&center&&基于HTML5的聊天室&/h2&&div align=&center& style=&width: 100%;height: 700&&&div id=&chat&& &div id=&up&&
&textarea type=&text& style=&width: 100%;height: 100%;& readonly=&readonly& id=&receive&&&/textarea& &/div& &div id=&down&&
&textarea type=&text& style=&width: 100%;height: 100%;& id=&send&&&/textarea& &/div&&/div&&input type=&button& value=http://blog.csdn.net/baiyanglu/article/details/&开始& class=""> com.baiyang.lc.import java.io.IOEimport java.nio.ByteBimport java.nio.CharBimport java.text.SimpleDateFimport java.util.Dimport java.util.HashMimport java.util.Mimport java.util.Simport javax.servlet.annotation.WebSimport javax.servlet.http.HttpServletRimport org..catalina.websocket.Iimport org..catalina.websocket.StreamIimport org.apache.catalina.websocket.WebSocketSimport org.apache.catalina.websocket.WsO@WebServlet(&/chat&)public class ChatWebSocketServlet extends WebSocketServlet { private final Map&Integer, WsOutbound& map = new HashMap&Integer, WsOutbound&(); /**
*/ private static final long serialUID = -9079067L; @Override protected StreamInbound createWebSocketInbound(String arg0, HttpServletRequest request) {
return new ChatMessageInbound(); } class ChatMessageInbound extends MessageInbound {
protected void onOpen(WsOutbound outbound) {
map.put(outbound.hashCode(), outbound);
super.onOpen(outbound);
protected void onClose(int status) {
map.remove(getWsOutbound().hashCode());
Set&Integer& keys = map.keySet();
super.onClose(status);
protected void onBinaryMessage(ByteBuffer buffer) throws IOException {
// TODO Auto-generated method stub
protected void onTextMessage(CharBuffer buffer) throws IOException {
String msg = buffer.toString();
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat(&HH:mm:ss&);
msg = &匿名用户
& + sdf.mat(date) + &\n& +
broadcast(msg);
private void broadcast(String msg) {
Set&Integer& set = map.keySet();
(Integer integer : set) {
WsOutbound outbound = map.get(integer);
CharBuffer buffer = CharBuffer.wrap(msg);
outbound.writeTextMessage(buffer);
outbound.flush();
} catch (IOException e) {
e.printStackTrace();}

我要回帖

更多关于 java聊天室私聊的代码 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信