(3)websocket实现单聊和群聊
生活随笔
收集整理的這篇文章主要介紹了
(3)websocket实现单聊和群聊
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1 資源下載地址? http://download.csdn.net/detail/jianfpeng241241/9325049
2? 群聊圖
? 2.1 zhangsan 發(fā)給所有人的圖
?????
?? 2.2 發(fā)送成功后?
?? zhangsan的界面如下
?lisi的界面如下
wangwu的界面如下
3 單聊圖
?3.1 zhangsan發(fā)送信息圖如下
?3.2發(fā)送成功后
?zhangsan界面如下
lisi界面如下
wangwu界面如下
4?項(xiàng)目結(jié)構(gòu)圖
?
5 代碼
?5.1 ChartMessage.java
package com.web.message;import java.text.SimpleDateFormat; import java.util.Date; import java.util.List;import com.google.gson.Gson;public class ChartMessage {private int type; // 單聊 type = 1 ,type =2 群聊private String from; //由誰(shuí)發(fā)的private List<String> to; //發(fā)給誰(shuí)private String content; //聊天內(nèi)容private String welcome; //進(jìn)聊天室和離開(kāi)聊天室提示信息private List<String> usernames ; //用戶(hù)列表名字private List<String> sessionUsernames;//websocket session名字private static Gson gson = new Gson();public ChartMessage(){}public ChartMessage(String welcome,List<String> usernames ){this.welcome = welcome;this.usernames = usernames;}public int getType() {return type;}public void setType(int type) {this.type = type;}public String getFrom() {return from;}public void setFrom(String from) {this.from = from;}public List<String> getTo() {return to;}public void setTo(List<String> to) {this.to = to;}public String getContent() {return content;}public void setContent(String content) {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" +from+" said : " + content;}public String getChartMessageToJson(){return gson.toJson(this);}public List<String> getUsernames() {return usernames;}public void setUsernames(List<String> usernames) {this.usernames = usernames;}public String getWelcome() {return welcome;}public void setWelcome(String welcome) {this.welcome = welcome;}public List<String> getSessionUsernames() {return sessionUsernames;}public void setSessionUsernames(List<String> sessionUsernames) {this.sessionUsernames = sessionUsernames;}}
5.2 Login.java
5.3 EchoSocket.java
?
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{//注解的方式 啟動(dòng)public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> scan) {System.out.println("-------------websoket start-----------------");System.out.println("scan.size() = " + scan.size());return scan; //必須要返回scan,否則會(huì)造成連接失敗}//接口方式啟動(dòng)public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> arg0) {return null;}}
?
5.5 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>
?
5.6 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}"; // 打開(kāi)管道 ,ws://localhost:8080/項(xiàng)目名/@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) { //創(chuàng)建websocket同時(shí),接收服務(wù)器發(fā)給客服端的消息if(event!=null){//將json字符串轉(zhuǎn)為對(duì)象eval("var msg="+event.data+";"); //得到對(duì)象里面的值var welcome = msg.welcome;var content = msg.content;var usernames = msg.usernames;//為聊天區(qū)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;}//為用戶(hù)列表區(qū)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 <input name='msgCheckBox' disabled='true' type='checkbox' value='"+usernames[i]+"'> <span style='color: red'>" + usernames[i]+"</span></br>";}else{userListTD.innerHTML += "\r\n <input name='msgCheckBox' type='checkbox' value='"+usernames[i]+"'>" + usernames[i]+"</br>";}}}}};}};sendMessage = function(){ //發(fā)送信息if(ws!=null){var checkNumber = 0 ; // 被選中復(fù)選框的個(gè)數(shù)var checkedUsernameArray = new Array(); // 被選中的復(fù)選框名字var checkBoxs = document.getElementsByName("msgCheckBox");for(var i = 0 ; i < checkBoxs.length ; i++ ){ var checkbox = checkBoxs[i];if(checkbox.checked == true){checkNumber ++;checkedUsernameArray.push(checkbox.value) ;}}// alert("checkedUsernameArray = " + checkedUsernameArray);var type; // 單聊 type = 1 ,type =2 群聊if(checkNumber > 0 ) { // 單聊 type = 1 type = 1;}else{ //群聊type = 2; }var sendMessageInput = document.getElementById("sendMessageTextArea");var msg = sendMessageInput.value; /*1 發(fā)送對(duì)象有哪些2 發(fā)送的類(lèi)型 單聊/群聊3 內(nèi)容*/var msgObj={type:type,from:'${requestScope.username}',to:checkedUsernameArray,content:msg};//將msgOjb對(duì)象轉(zhuǎn)為jsonvar json = JSON.stringify(msgObj);ws.send(json);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()">發(fā)送</button></td></tr></table></body> </html>
?
5.7 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">用戶(hù)名:<input type="text" name="username"/><input type="submit" value="登錄"/></form></body> </html>
?
?
?
???
總結(jié)
以上是生活随笔為你收集整理的(3)websocket实现单聊和群聊的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: (2) websocket 实现群聊
- 下一篇: ( 一 ) Jpbm环境的搭建