WebSocket實現簡單的web聊天室

x286 9年前發布 | 13K 次閱讀 Java WebSocket
1.需要Tomcat7.0所以服務器
2.需要JDK7.0
3.手工加入Tomcat7.0中lib目錄下的一下三個包catalina.jar、tomcat-coyote.jar、websocket-api.jar
4.項目部署后,請將服務器中當前項目下的catalina.jar、tomcat-coyote.jar、websocket-api.jar三個包刪除。
5.項目目錄結構如下
圖片


Servlet代碼
package com.yc.websockets;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.StreamInbound;
import org.apache.catalina.websocket.WebSocketServlet;
import org.apache.catalina.websocket.WsOutbound;

@SuppressWarnings({"deprecation","unused", "serial"})
public class WebSocketTest extends WebSocketServlet {
private static List<MyMessageInbound> userList = new ArrayList<MyMessageInbound>();
private HttpSession session;

    @Override
    protected StreamInbound createWebSocketInbound(String str, HttpServletRequest request) {
     session=request.getSession();
        return new MyMessageInbound();
    }

    private class MyMessageInbound extends MessageInbound {
        WsOutbound myoutbound;

        /**
         * 當用戶登錄時,WebSocket握手完成,創建完畢,WsOutbound用于向客戶端發送數據
         */
public void onOpen(WsOutbound outbound) {
            try {
                System.out.println("Open Client.");
                this.myoutbound = outbound;
                userList.add(this); //添加當前用戶

                //向客服端發送信息
                outbound.writeTextMessage(CharBuffer.wrap("Hello!"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

/**
 * 用戶退出時,WebSocket關閉事件,參數status應該來自org.apache.catalina.websocket.Constants
 * 中定義的幾個常量,可以參考文檔或者核對一下Tomcat的源碼
 */
        @Override
        public void onClose(int status) {
            userList.remove(this); //移除當前用戶
        }

       /**
        * 接受用戶發過來的信息,有文本消息數據到達
        */
        @Override
        public void onTextMessage(CharBuffer cb) throws IOException {
            for (MyMessageInbound mmib:userList){ //循環向所有在線用戶發送當前用戶的信息
                CharBuffer buffer = CharBuffer.wrap(cb);
                mmib.myoutbound.writeTextMessage(buffer); //調用指定用戶的發送方法發送當前用戶信息
                mmib.myoutbound.flush(); //清空緩存
            }
        }

        /**
         * 有二進制消息數據到達,暫時沒研究出這個函數什么情況下觸發,js的WebSocket按理說應該只能send文本信息才對
         */
        @Override
        public void onBinaryMessage(ByteBuffer bb) throws IOException {
        }
    }
}




web.xml配置文件 
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
<display-name></display-name>

<servlet>
<servlet-name>webServlet</servlet-name>
<servlet-class>com.yc.websockets.WebSocketTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>webServlet</servlet-name>
<url-pattern>/webServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>


index.html
<!DOCTYPE html>
<html>
<head>
<meta charset=UTF-8>
<title>Tomcat WebSocket Chat</title>
<script>
//設定WebSocket,注意協議是ws,請求是指向對應的WebSocketServlet的
/*設定WebSocket,注意協議是ws,請求是指向對應的WebSocketServlet的
var url = "ws://127.0.0.1:8080/j2ee6/echo.ws";
// 創建WebSocket實例,下面那個MozWebSocket是Firefox的實現
if ('WebSocket' in window) {
ws = new WebSocket(url);
} else if ('MozWebSocket' in window) {
ws = new MozWebSocket(url);
} else {
alert('Unsupported.');
return;
}*/
var ws = new WebSocket("ws://218.196.14.208:8080/webSocket/webServlet");

//WebSocket握手完成,連接成功的回調
//有個疑問,按理說new WebSocket的時候就會開始連接了,如果在設置onopen以前連接成功,是否還會觸發這個回調
ws.onopen = function() {
//請求成功
};

//收到服務器發送的文本消息, event.data表示文本內容
ws.onmessage = function(message) {
document.getElementById("talkInfo").innerHTML+=message.data+"<hr style='border: 1px dashed #CCC'/>";
};

//關閉WebSocket的回調
ws.onclose = function() {
//alert('Closed!');
};

// 通過WebSocket想向服務器發送一個文本信息
function postToServer() {
ws.send(document.getElementById("content").value);
document.getElementById("content").value = "";
}

//關閉WebSocket
function closeConnect() {
ws.close();
}
</script>
<style>
* {
margin: 0 auto;
padding: 0px;
font-size: 12px;
font-family: "微軟雅黑";
line-height: 26px;
}

#bigbox {
margin:0px auto;
padding:0px;
width:70%;
}

#talkInfo{
width:100%;
height:500px;
border:1px solid red;
overflow: scorll;
}

#operation{
width:100%;
height:30px;
margin-top:10px;
}

#content{
height:30px;
line-height:30px;
}
</style>
</head>
<body>
<div id="bigbox">
<div id="talkInfo"></div>
<div id="operation">
<center>
<input type="text" name="content" id="content" size="100"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value=" &nbsp;發送&nbsp; " onclick="postToServer()" />&nbsp;&nbsp;
<input type="button" value=" &nbsp;我閃 &nbsp; " onclick="closeConnect()" />
</center>
</div>
</div>
</body>
</html> 

 本文由用戶 x286 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!