使用websocket實如今線聊天功能

  很早之前爲了快速達到效果,使用輪詢實現了在線聊天功能,後來無心接觸了socket,關於socket個人理解是進程間通訊,首先要有服務器跟客戶端,服務的啓動監聽某ip端口定位該進程,客戶端開啓socket分配ip端口鏈接服務端ip端口,因而兩個進程間即可以通訊了。下面簡單畫個圖理解。javascript

  but,今天仍是準備分享websocket的使用,先上效果,再貼代碼。java

  第一步啓動socket服務。jquery

  而後鏈接客戶端鏈接服務器,加入聊天室,分別使用googel(白玉京,沈浪),火狐(楚留香),ie(李尋歡)進行測試,效果以下。web

  *瀏覽器

*****************斷開一下。服務器

 

  ******************斷開一下。websocket

 

  下面是本次測試源碼。session

  服務端:app

 public class TestWebSocketController : Controller
    {
        WebSocketServer server;
        List<SessionInfo> listSession = new List<SessionInfo>();
        public ActionResult Index()
        {
            return View();
        }
        //服務啓動
        public string Start()
        {
            var ip = "192.168.1.106";
            var port = "1010";
            server = new WebSocketServer();
            if (!server.Setup(ip, int.Parse(port)))
            {
                return "WebSocket服務啓動Error";
            }
            //新的會話鏈接
            server.NewSessionConnected += SessionConnected;
            //會話關閉
            server.SessionClosed += SessionClosed;
            //新的消息接收
            server.NewMessageReceived += MessageReceived;
            if (!server.Start())
            {
                //處理監聽失敗消息
                return "error";
            }
            return "success";
        }

        /// <summary>
        /// 會話關閉
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            Debug.WriteLine("會話關閉,關閉緣由:{0}  來自:{1}  時間:{2:HH:MM:ss}", value, session.RemoteEndPoint, DateTime.Now);
            //SendMsgToRemotePoint(SessionId, SessionId + "已斷開");
            var sessionRemove = listSession.FirstOrDefault(s => s.SessionId == session.SessionID);
            listSession.Remove(sessionRemove);
        }
        /// <summary>
        /// 會話鏈接
        /// </summary>
        /// <param name="session"></param>
        private void SessionConnected(WebSocketSession session)
        {
            Debug.WriteLine("新的會話鏈接  來自:{0} SessionID:{1}  時間:{2:HH:MM:ss}", session.RemoteEndPoint, session.SessionID, DateTime.Now);
            listSession.Add(new SessionInfo { SessionId = session.SessionID, EndPoint = session.RemoteEndPoint.ToString() });
        }
        /// <summary>
        /// 消息接收
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private void MessageReceived(WebSocketSession session, string value)
        {
            //反序列化消息內容
            var message = JsonConvert.DeserializeObject<MessageInfo>(value);
            foreach (var item in listSession)
            {
                ///發送消息
                SendMsg(item.SessionId, string.Format("{0}發來消息:{1}", message.Name, message.Message));
            }
        }

        // <summary>
        /// 發送消息
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="msg"></param>
        private void SendMsg(string sessionId, string msg)
        {
            var appSession = server.GetAppSessionByID(sessionId);
            if (appSession != null)
                appSession.Send(msg);
        }
        public class MessageInfo
        {
            public string Name { get; set; }
            public string Message { get; set; }

        }
        public class SessionInfo
        {
            public string SessionId { get; set; }
            public string EndPoint { get; set; }
            //public string Name { get; set; }
        }
    }

  客戶端:socket

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<script src="../Scripts/jquery-1.8.2.js"></script>
<input type="text" id="txtName" />
<input type="button" value="加入聊天室" id="btnConnection" />
<input type="button" value="離開聊天室" id="btnDisConnection" />
<input type="text" id="txtInput" />
<input type="button" value="發送" id="btnSend" />
<div id="msg"></div>
<script language="javascript" type="text/javascript">
    var ws;
    var url = "ws://192.168.1.106:1010"
    $("#btnConnection").click(function () {
        if ("WebSocket" in window) {
            ws = new WebSocket(url);
        }
        else if ("MozWebSocket" in window) {
            ws = new MozWebSocket(url);
        }
        else
            alert("瀏覽器版本太低,請升級您的瀏覽器");
        //註冊各種回調
        ws.onopen = function () {
            $("#msg").append($("#txtName").val() + "加入聊天室<br />");
        }
        ws.onclose = function () {
            $("#msg").append($("#txtName").val() + "離開聊天室<br />");
        }
        ws.onerror = function () {
            $("#msg").append("數據傳輸發生錯誤<br />");
        }
        ws.onmessage = function (receiveMsg) {
            $("#msg").append(receiveMsg.data + "<br />");
        }
        //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket鏈接,防止鏈接還沒斷開就關閉窗口,server端會拋異常。
        window.onbeforeunload = function () {
            ws.close();
        }
    });
    //$("#btnDisConnection").click(function () {
    //    $("#msg").append($("#txtName").val() + "離開聊天室<br />");
    //    ws.close();
    //});
    $("#btnSend").click(function () {
        if (ws.readyState == WebSocket.OPEN) {
            var message = "{\"name\":\"" + $("#txtName").val() + "\",\"message\":\"" + $("#txtInput").val() + "\"}";
            ws.send(message);
        }
        else {
            $("#msg").text("Connection is Closed!");
        }
    });
</script>
相關文章
相關標籤/搜索