利用websocket快速实现多人聊天功能
j2ee7支持websocket协议,eclipse4.3 netbeans 7.3.1 这些ide 都已经开始支持.
但文档相对较少,下面利用netbeans 快速搭建一个多人聊天的功能
到https://netbeans.org/downloads/ 迅速下载一个
选择ALL的安装包 224M 下载完后快速安装。
新建一个j2ee项目
<!--[if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/></v:shapetype><v:shape id="图片_x0020_1" o:spid="_x0000_i1027" type="#_x0000_t75" style='width:415.5pt;height:227.25pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\ASUS\AppData\Local\Temp\msohtmlclip1\01\clip_image001.png" o:title=""/></v:shape><![endif]--><!--[if !vml]--><!--[endif]-->
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]-->
<!--[if gte vml 1]><v:shape id="图片_x0020_17" o:spid="_x0000_i1025" type="#_x0000_t75" style='width:370.5pt; height:396.75pt;visibility:visible;mso-wrap-style:square'> <v:imagedata src="file:///C:\Users\ASUS\AppData\Local\Temp\msohtmlclip1\01\clip_image005.png" o:title=""/></v:shape><![endif]--><!--[if !vml]--><!--[endif]-->
附源码: