java websocket的开发案例与注意事项
来源:互联网 发布:无法连接mysql数据库 编辑:程序博客网 时间:2024/05/22 11:59
第一步:源码
/*
* 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 com.websocket.chat;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;
import javax.servlet.http.HttpServletRequest;
import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;
/**
* Example web socket servlet for chat.
*/
public class ChatWebSocketServlet extends WebSocketServlet {
private static final long serialVersionUID = 1L;
private static final String GUEST_PREFIX = "Guest";
private final AtomicInteger connectionIds = new AtomicInteger(0);
private final Set<ChatMessageInbound> connections =
new CopyOnWriteArraySet<ChatMessageInbound>();
@Override
protected StreamInbound createWebSocketInbound(String subProtocol,
HttpServletRequest request) {
return new ChatMessageInbound(connectionIds.incrementAndGet());
}
private final class ChatMessageInbound extends MessageInbound {
private final String nickname;
private ChatMessageInbound(int id) {
this.nickname = GUEST_PREFIX + id;
}
@Override
protected void onOpen(WsOutbound outbound) {
connections.add(this);
String message = String.format("* %s %s",
nickname, "has joined.");
broadcast(message);
}
@Override
protected void onClose(int status) {
connections.remove(this);
String message = String.format("* %s %s",
nickname, "has disconnected.");
broadcast(message);
}
@Override
protected void onBinaryMessage(ByteBuffer message) throws IOException {
throw new UnsupportedOperationException(
"Binary message not supported.");
}
@Override
protected void onTextMessage(CharBuffer message) throws IOException {
// Never trust the client
String filteredMessage = String.format("%s: %s",
nickname, "");
broadcast(filteredMessage);
}
private void broadcast(String message) {
for (ChatMessageInbound connection : connections) {
try {
CharBuffer buffer = CharBuffer.wrap(message);
connection.getWsOutbound().writeTextMessage(buffer);
} catch (IOException ignore) {
// Ignore
}
}
}
}
}
第二步 websocket部署
<servlet>
<servlet-name>wsChat</servlet-name>
<servlet-class>com.websocket.chat.ChatWebSocketServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>wsChat</servlet-name>
<url-pattern>/websocket/chat</url-pattern>
</servlet-mapping>
第三步 html5
<!--
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.
-->
<!DOCTYPE html>
<html>
<head>
<title>Apache Tomcat WebSocket Examples: Chat</title>
<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="text/javascript">
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 is not supported by this browser.');
return;
}
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 = null;
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 +'/btc/websocket/chat');
} else {
Chat.connect('wss://' + window.location.host + '/btc/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();
</script>
</head>
<body>
<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></noscript>
<div>
<p>
<input type="text" placeholder="type and press enter to chat" id="chat">
</p>
<div id="console-container">
<div id="console"></div>
</div>
</div>
</body>
</html>
第四步 需要引入相关jar : tomcat-coyote.jar,catalina.jar .
最后编译,然后运行。访问chat.html。注意红色的标记。
如有不懂,请加入QQ群 :211202664
- java websocket的开发案例与注意事项
- WebSocket与SpringMVC集成案例
- Js WebScoket与Java WebSocket的通信
- WebSocket与Java
- WebSocket与Java
- WebSocket与Java
- websocket 与java
- websocket与Java实例
- apache websocket 聊天室的简单案例
- SuperWebSocket服务器端开发,实现c#与webSocket的完美结合
- java-websocket 服务端 开发中遇到的问题
- GPRS模块与单片机开发的注意事项
- VS2010开发.cpp与.c的注意事项
- Java基础与案例开发详解のjava平台的体系结构
- Java基础与案例开发详解のjava技术的两个核心
- WebSocket的java实现
- java的WebSocket Demo
- 学习java websocket的
- mysqldump Tips
- Qt和MFC比较
- To the Max - POJ 1050 dp
- Android应用程序升级后自动进入新版本
- button 里面的文字换行后位置会浮动
- java websocket的开发案例与注意事项
- android移植pppoe实现拨号上网全过程
- Handling Configuration Changes with Fragments
- 大话设计模式之依赖倒转原则
- 在本地计算机端口被占用而无法启动MySql,解决办法
- 关于Flash Builder的debug和release
- startActivityForResult
- Android中Preference的使用以及监听事件分析
- JAVA中Get和Post请求的区别