Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to create a small chat room with webSocket and Swoole

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

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 () {}).

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report