J2EE7已经发布了 参照 http://www.iteye.com/news/27980
j2ee7支持websocket协议,eclipse4.3 netbeans 7.3.1 这些ide 都已经开始支持.
但文档相对较少,下面利用netbeans 快速搭建一个多人聊天的功能
到https://netbeans.org/downloads/ 迅速下载一个
选择ALL的安装包 224M 下载完后快速安装。
新建一个j2ee项目
web页添加chat.hml 建立和websocket 连接
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://localhost:8080/EnterpriseApplication1-war/chat');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML += '<br />' + event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML = '已连接到服务器......<br/>';
}
function onError(event) {
alert(event.data);
}
function start() {
webSocket.send('hello');
return false;
}
function send(){
var talk = $('talk');
var nike = $('nike');
webSocket.send('<strong style="color:red">'+nike.value+':</strong>'+talk.value);
}
function $(id){
return document.getElementById(id);
}
</script>
服务端代码
@ServerEndpoint("/chat")
public class WebSocketTest {
@OnMessage
public void onMessage(String message, Session session)
throws IOException, InterruptedException {
// Print the client message for testing purposes
System.out.println("Received: " + message);
//获取所有存活会话,并相应消息
Set<Session> set=session.getOpenSessions();
Iterator<Session> it=set.iterator();
//迭代遍历
while(it.hasNext()){
Session everySession=it.next();
if(everySession.isOpen()){
everySession.getBasicRemote().sendText(message);
}
}
在项目上点击运行,运行netbeans自带的glassfish 4
多开继续页面 访问路径http://localhost:8080/EnterpriseApplication1-war/chat.html
可以看到如下效果
<!--[if gte vml 1]><v:shape id="图片_x0020_14" o:spid="_x0000_i1026" type="#_x0000_t75" style='width:405.75pt; height:491.25pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\ASUS\AppData\Local\Temp\msohtmlclip1\01\clip_image003.png" o:title=""/> </v:shape><![endif]--><!--[if !vml]--><!--[endif]-->
附源码: