(2) websocket 实现群聊
生活随笔
收集整理的這篇文章主要介紹了
(2) websocket 实现群聊
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 開發環境請見? "基于tomcat7和jdk1.7的websocket啟動 "? ,另外 源碼下載地址為 : http://download.csdn.net/detail/jianfpeng241241/9323549
2 項目結構圖
?
3 Message.java
package com.web.message;import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List;import com.google.gson.Gson;/** 定義傳播的信息的結構* */ public class Message {private String content;private String welcome;private List<String> usernames;private static Gson gson = new Gson();public String getWelcome() {return welcome;}public Message(){}public Message(String welcome,List<String> usernames){this.welcome = welcome;this.usernames = usernames;}public void setWelcome(String welcome) {this.welcome = welcome;}public List<String> getUsernames() {return usernames;}public void setUsernames(List<String> usernames) {this.usernames = usernames;}public String toJson(){return gson.toJson(this);}public String getContent() {return content;}public void setContent(String content,String username) {SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String time = sdf.format(new Date());this.content = "\r\n\r\n" +time +"\r\n" +username+" said : " + content;}public static void main(String args[]){SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");String time = sdf.format(new Date());System.out.println(time);} }
4? Login.java
?
5 EchoSocket.java
package com.webSocket.client;import java.io.IOException; import java.util.ArrayList; import java.util.List;import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint;import com.web.message.Message;@ServerEndpoint("/echo") public class EchoSocket {private static List<String> usernames = new ArrayList<String>();private static List<Session> sessions = new ArrayList<Session>();private String username; private Session session;@OnOpenpublic void open(Session session){ //打開websocketSystem.out.println("userid = "+session.getId());String string = session.getQueryString();this.username = string.split("=")[1];this.usernames.add(this.username);this.sessions.add(session);String welcome = "歡迎"+this.username+"加入聊天室";Message message = new Message(welcome,this.usernames);this.broadcast(this.sessions,message.toJson());}@OnClosepublic void close(Session session){ //關閉websocketthis.sessions.remove(session);this.usernames.remove(this.username);String goMsg = this.username+"已經離開聊天室";Message message = new Message(goMsg,this.usernames);this.broadcast(this.sessions,message.toJson());System.out.println("websocket is close");}@OnMessagepublic void message(Session session,String msg){//接收客服端信息//System.out.println("客服端信息為 : " + message);if (session.isOpen()) {Message message = new Message();message.setUsernames(this.usernames);message.setContent(msg,this.username);this.broadcast(this.sessions,message.toJson());}}public List<String> getUsernames() {return usernames;}public List<Session> getSessions() {return sessions;}private void broadcast(List<Session> sessionsList,String msg) { //廣播給其它人if(sessionsList.size() > 0){for(int i = 0 ; i < sessionsList.size() ; i++){try {sessionsList.get(i).getBasicRemote().sendText(msg);} catch (IOException e) {System.out.println("EchoSocket.java broadcast method ,廣播失敗 ");e.printStackTrace();}}}}}
?
6 DemeConfig.java
?
package com.webSocket.config;import java.util.Set;import javax.websocket.Endpoint; import javax.websocket.server.ServerApplicationConfig; import javax.websocket.server.ServerEndpointConfig;public class DemeConfig implements ServerApplicationConfig{//注解的方式 啟動public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scan) {System.out.println("-------------websoket start-----------------");System.out.println("scan.size() = " + scan.size());return scan; //必須要返回scan,否則會造成連接失敗}//接口方式啟動public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) {return null;}}?
7 web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet><description>This is the description of my J2EE component</description><display-name>This is the display name of my J2EE component</display-name><servlet-name>Login</servlet-name><servlet-class>com.web.servlet.Login</servlet-class></servlet><servlet-mapping><servlet-name>Login</servlet-name><url-pattern>/servlet/Login</url-pattern></servlet-mapping><welcome-file-list><welcome-file>login.jsp</welcome-file></welcome-file-list> </web-app>
?
8 chart.jsp?
<%@ page language="java" import="java.util.*,javax.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>My JSP 'index.jsp' starting page</title></head><body><script type="text/javascript">var ws=null; var target = "ws://"+window.location.host+"/webSocketTest/echo?username=${requestScope.username}"; // 打開管道 ,ws://localhost:8080/項目名/@ServerEndpoint名字window.οnlοad=function(){if(ws==null){if ('WebSocket' in window) {ws = new WebSocket(target);} else if ('MozWebSocket' in window) {ws = new MozWebSocket(target);} else {alert('WebSocket is not supported by this browser.');return;}ws.onmessage = function (event) { //創建websocket同時,接收服務器發給客服端的消息if(event!=null){//將json字符串轉為對象eval("var msg="+event.data+";"); //得到對象里面的值var welcome = msg.welcome;var content = msg.content;var usernames = msg.usernames;//為聊天區teaxarea賦值var textArea = document.getElementById("content");if(undefined!=welcome){textArea.value = textArea.value + "\r\n"+welcome;}if(undefined!=content){textArea.value = textArea.value + "\r\n"+content;}//為用戶列表區TD賦值var userListTD = document.getElementById("userList");userListTD.innerHTML="";for(var i = 0 ; i < usernames.length; i++){if(undefined!=usernames[i]){if("${requestScope.username}" == usernames[i]){userListTD.innerHTML += "\r\n <span style='color: red'>" + usernames[i]+"</span></br>";}else{userListTD.innerHTML += "\r\n" + usernames[i]+"</br>";}}}}};}};sendMessage = function(){ //發送信息if(ws!=null){var sendMessageInput = document.getElementById("sendMessageTextArea");var msg = sendMessageInput.value;ws.send(msg);sendMessageInput.value ="";}else{alert("websocket is null , please create a websocket");}}</script><table cellpadding="0" cellspacing="0" border="1" width="500px" height="400px"><tr><td><textarea id="content" rows="10" cols=50"></textarea></td><td id="userList" width="150px" align="center"></td></tr><tr><td colspan="2"><textarea id="sendMessageTextArea" rows="5" cols=50"></textarea><button οnclick="sendMessage()">發送</button></td></tr></table></body> </html>
?
9 login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>login</title></head><body><form action="<%=request.getContextPath()%>/servlet/Login" method="get">用戶名:<input type="text" name="username"/><input type="submit" value="登錄"/></form></body> </html>
?
?
總結
以上是生活随笔為你收集整理的(2) websocket 实现群聊的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (1) 基于tomcat7和jdk1.7
- 下一篇: (3)websocket实现单聊和群聊