关键词搜索

源码搜索 ×
×

Node.js笔记-使用socket.io构建websocket聊天室

发布2021-11-16浏览659次

详情内容

先安装socket.io

npm install socket.io 

服务端代码:

  1. let app = require('http').createServer();
  2. let io = require('socket.io')(app, { cors: true });
  3. let port = 3000;
  4. let clientCount = 0;
  5. app.listen(port);
  6. io.on('connection', function (socket) {
  7. clientCount++;
  8. socket.nickname = 'user' + clientCount;
  9. io.emit('enter', socket.nickname + ' comes in');
  10. socket.on('message', function (str) {
  11. io.emit('message', socket.nickname + ' says: ' + str);
  12. })
  13. socket.on('disconnect', function () {
  14. io.emit('leave', socket.nickname + ' left');
  15. })
  16. });
  17. console.log("Websocket server listening on port = " + port)

客户端代码:

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>WebSocketIO</title>
  6. <script src="https://cdn.socket.io/4.0.1/socket.io.js"></script>
  7. </head>
  8. <body>
  9. <h1>Chat Room</h1>
  10. <input id="sendTxt" type="text" />
  11. <button id="sendBtn">发送</button>
  12. <script type="text/javascript">
  13. let socket = io("ws://localhost:3000/");
  14. function showMessage(str, type){
  15. let div = document.createElement('div');
  16. div.innerHTML = str;
  17. if(type == "enter"){
  18. div.style.color = "blue";
  19. }
  20. else if(type == "leave"){
  21. div.style.color = "red";
  22. }
  23. document.body.appendChild(div);
  24. }
  25. document.getElementById("sendBtn").onclick = function () {
  26. let txt = document.getElementById("sendTxt").value;
  27. if(txt){
  28. console.log(txt)
  29. socket.emit('message', txt);
  30. }
  31. }
  32. socket.on('enter', function (data) {
  33. showMessage(data, 'enter');
  34. })
  35. socket.on('message', function (data) {
  36. showMessage(data, 'message');
  37. })
  38. socket.on('leave', function (data) {
  39. showMessage(data, 'leave');
  40. })
  41. </script>
  42. </body>
  43. </html>

运行截图如下:

 退出:

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载