How to create a small chat room with webSocket and Swoole
This article mainly introduces the relevant knowledge of how to use webSocket and Swoole to create a small chat room, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to create a small chat room with webSocket and Swoole. Let's take a look.
Front-end page code:
Call the workers' chat room. Content {height: 400px; max-width: 400px; overflow: auto; border-radius: 5px; border: 1px solid # f0f0f0;}
Chat area
Hello, worker: nickname
This time connect to FD:
P:last-child ") .after ('
The server is connected, let's start chatting
'); websocket.send (data);}; / / Link broken websocket.onclose = function (evt) {$("# content > p:last-child") .after ('
The server has been disconnected, please reconnect
');}; / / after receiving the server message websocket.onmessage = function (evt) {/ / after a successful handshake, the server will receive the fd returned by the server. The msgType = 1 / / string will be formatted as json var data = eval (' ('+ evt.data +')'); / / console.log (evt.data) Switch (data.msgType) {case 1: thisFd = data.fd; $('# fd-samp') .html (thisFd); $('# fd') .val (thisFd); break Case 2: if (data.nickname = = nickname) {data.nickname ='I';} $("# content > p:last-child") .after ('
'+ data.nickname +' says in'+ data.time +':
'+ data.data +'
'); / / receives a message that automatically hits bottom scrolltest (); break;}}; / / Server exception websocket.onerror = function (evt, e) {$("# content > p:last-child") .server ('
Server exception
');}; / / heartbeat, added function heartbeat () {var data = {' msgType': 'ping',} / / generate json to facilitate backend reception and use var data = JSON.stringify (data); websocket.send (data);} / 30 seconds once setInterval (heartbeat, 30000)
Server code
Cooperation programs, all need to be in Co\ run (function () {}).