A long time ago, in order to achieve the effect quickly, I used polling to implement the online chat function. Later, I accidentally contacted socket. Regarding socket, my understanding is between-process communication. First, there must be a server and a client. The service starts and listens to a certain IP port to locate the process. The client opens the socket allocates the IP port to connect to the IP port on the server, so the communication between the two processes can be done. Let’s draw a simple picture below to understand.
But, today I am still planning to share the use of websocket, first put the effect, and then paste the code.
The first step is to start the socket service.
Then connect to the client and connect to the server, join the chat room, and use googel (Bai Yujing, Shen Lang), Firefox (Chu Liuxiang), and I (Li Xunhuan) to test, and the effect is as follows.
*
*********************Disconnect.
************************Disconnect.
Below is the source code of this test.
Server:
public class TestWebSocketController : Controller { WebSocketServer server; List<SessionInfo> listSession = new List<SessionInfo>(); public ActionResult Index() { return View(); } //Service start public string Start() { var ip = "192.168.1.106"; var port = "1010"; server = new WebSocketServer(); if (!server.Setup(ip, int.Parse(port))) { return "WebSocket service start Error"; } //New session connection server.NewSessionConnected += SessionConnected; //Session close server.SessionClosed += SessionClosed; //New message receiving server.NewMessageReceived += MessageReceived; if (!server.Start()) { //Processing listening failure message return "error"; } return "success"; } /// <summary> /// Session close/// </summary> /// <param name="session"></param> /// <param name="value"></param> private void SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason) { Debug.WriteLine("Session closes, reason for closing: {0} From: {1} Time: {2:HH:MM:ss}", value, session.RemoteEndPoint, DateTime.Now); //SendMsgToRemotePoint(SessionId, SessionId + "Disconnected"); var sessionRemove = listSession.FirstOrDefault(s => s.SessionId == session.SessionID); listSession.Remove(sessionRemove); } /// <summary> /// Session Connection/// </summary> /// <param name="session"></param> private void SessionConnected(WebSocketSession session) { Debug.WriteLine("New SessionID:{1} Time:{2:HH:MM:ss}", session.RemoteEndPoint, session.SessionID, DateTime.Now); listSession.Add(new SessionInfo { SessionId = session.SessionID, EndPoint = session.RemoteEndPoint.ToString() }); } /// <summary> /// Message Receive/// </summary> /// <param name="session"></param> /// <param name="value"></param> private void MessageReceived(WebSocketSession session, string value) { //Deserialize message content var message = JsonConvert.DeserializeObject<MessageInfo>(value); foreach (var item in listSession) { ///Send message SendMsg(item.SessionId, string.Format("{0}Send message: {1}", message.Name, message.Message)); } } // <summary> /// Send message/// </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; } } }Client:
@{ ViewBag.Title = "Index";}<h2>Index</h2><script src="../Scripts/jquery-1.8.2.js"></script><input type="text" id="txtName" /><input type="button" value="Join the chat room" id="btnConnection" /><input type="button" value="Leave the chat room" id="btnDisConnection" /><input type="text" id="txtInput" /><input type="button" value="Send" 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("The browser version is too low, please upgrade your browser"); //Register various callbacks ws.onopen = function () { $("#msg").append($("#txtName").val() + "Add to the chat room<br />"); } ws.onclose = function () { $("#msg").append($("#txtName").val() + "Leave the chat room<br />"); } ws.onmessage = function (receiveMsg) { $("#msg").append(receiveMsg.data + "<br />"); } // Listen to the window closing event. When the window is closed, actively close the websocket connection to prevent the window from closing before the connection is disconnected. The server side will throw an exception. window.onbeforeunload = function () { ws.close(); } }); //$("#btnDisConnection").click(function () { // $("#msg").append($("#txtName").val() + "Leave the chat room<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>Summarize
The above is the use of websocket in Java to implement online chat function that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!