HTML5新特性之WebSocket实例(可下载)

运行环境:jdk1.7+,tomcat7+

需要的jar:websocket-api.jar(tomcat7+中有)

客户端chat.html:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://www.w3school.com.cn/jquery/jquery-1.11.1.min.js"></script>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>在线群聊</title>
<script type="text/javascript">
    var timestamp=Date.parse(new Date());
    var webSocket=new WebSocket("ws://192.168.20.29:8080/websocket-demo/websocket/"+timestamp);
 
    webSocket.onerror = function(event) {
       alert(event.data);
    };
 
    webSocket.onopen = function(event) {
      document.getElementById("list").innerHTML="连接建立成功!";
    };
 
    webSocket.onmessage = function(event) {
      document.getElementById("list").innerHTML+="<br/>" + event.data;
    };
    
    function sendMessage() {
      var msg=document.getElementById("nickname").value+":"+document.getElementById("textarea").value;
      document.getElementById("textarea").value="";
      webSocket.send(msg);
    }
 </script>
</head>
<body>
<div align="left" style="color: green" id="top">---------------消息记录----------------</div>
<div align="left" id="list"></div>
<div align="left" style="color: green" id="bottom">---------------消息记录----------------</div>
<div align="left">
      <textarea name="textarea" id="textarea" cols="45" rows="5"></textarea><br/>
          
                  您的昵称:
      <input width="10" type="text" name="nickname" id="nickname"/>
      <input width="50" type="button" name="button" id="button" οnclick="sendMessage()" value=" 发 送 " />
      <br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
</div>

</body>

</html>

服务端WebSocketTest类:

package com.web.demo;
 
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

@ServerEndpoint("/websocket/{userId}")
public class WebSocketTest {
 
	private static Map<String, Session> sessionMap=new HashMap<String, Session>();//在线的客户端session集合,只在第一次new的时候初始化。
  /**
   * 接收信息事件
   * @param message 客户端发来的消息
   * @param session 当前会话
   */
  @OnMessage
  public void onMessage(String message,Session session,@PathParam(value="userId")String userId)throws Exception {
   
    try {
    	Iterator<String> it = sessionMap.keySet().iterator();
    	//循环给每个客户端发送信息
    	while(it.hasNext()){
    		String key = (String) it.next();
    		Session value = sessionMap.get(key);
    		value.getBasicRemote().sendText(message);
    	}
    	 System.out.println("用户"+userId+"说:"+message+"。");
    	 System.out.println("当前在线人数:"+sessionMap.size());
	} catch (Exception e) {
		System.out.println("接收消息事件异常!");
	}
  }
  
  /**
   * 打开连接事件
 * @throws Exception 
   */
  @OnOpen
  public void onOpen(Session session,@PathParam(value="userId")String userId) throws Exception {
    System.out.println("打开连接成功!");
    sessionMap.put(userId, session);
    System.out.println("用户"+userId+"进来了。。。");
    System.out.println("当前在线人数:"+sessionMap.size());
  }
 
  /**
   * 关闭连接事件
   */
  @OnClose
  public void onClose(Session session,@PathParam(value="userId")String userId) {
    System.out.println("关闭连接成功!");
    System.out.println("用户"+userId+"离开了。。。");
    sessionMap.remove(userId);
    System.out.println("当前在线人数:"+sessionMap.size());
  }
  
  /**
   * 错误信息响应事件
   * @param session
   * @param throwable
   */
  @OnError
  public void OnError(Session session,Throwable throwable,@PathParam(value="userId")String userId) {
	    System.out.println("异常:"+throwable.getMessage());
	    System.out.println("用户"+userId+"的连接出现了错误。。。");
	    System.out.println("当前在线人数:"+sessionMap.size());
  }
  
}
websocket-demo项目下载地址:

http://download.csdn.net/download/xuxile/9395620

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值