当前位置:   article > 正文

简单的websocket服务_简单websocket服务

简单websocket服务

socket_service.js  (node版本)

  1. let ws = require('ws');
  2. let socketServer = ws.Server;
  3. let uuid = require('uuid');
  4. let wss = new socketServer({port:8090})
  5. let User = require('./user.js');
  6. let clients = [];
  7. //广播所有的客户端消息
  8. function broadcastSend(message){
  9. clients.forEach((v,i)=>{
  10. if(v.ws.readState == ws.OPEN){
  11. v.ws.send(JSON.stringify({
  12. "message":message
  13. }))
  14. }
  15. })
  16. }
  17. //开始舰艇端口以及数据
  18. wss.on('connection',function(ws){
  19. let client_uuid = uuid.v4();
  20. clients.push({
  21. "id":client_uuid,
  22. 'ws':ws,
  23. });
  24. console.log(`client ${client_uuid} connected`);
  25. //关闭服务
  26. function closeSocket(){
  27. for(var i=0;i<clients.length;i++){
  28. if(clients[i].id == client_uuid){
  29. clients.splice(i,1);
  30. }
  31. }
  32. }
  33. ws.on('message',function(message){
  34. clients.forEach((item)=>{
  35. item.ws.send(message);
  36. })
  37. //broadcastSend(message);
  38. })
  39. ws.on('close',function(){
  40. closeSocket()
  41. })
  42. })

socket_client.js(web版本)

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="google" content="notranslate" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <meta http-equiv="X-UA-Compatible" content="ie=edge">
  8. <title>Document</title>
  9. <script>
  10. window.onload = function(){
  11. var input = document.querySelector('.input');
  12. var btn = document.querySelector('.btn');
  13. var close_btn = document.querySelector('.close');
  14. var ws = new WebSocket("ws://localhost:8090");
  15. ws.onopen = function (e) {
  16. alert('Connection to server opened');
  17. }
  18. var data = 'data';
  19. ws.onmessage = function (data) {
  20. let info = JSON.parse(data.data).msg;
  21. let li = document.createElement('li');
  22. li.innerHTML = info;
  23. document.querySelector('.lists').appendChild(li);
  24. input.value = ''
  25. }
  26. ws.onclose = function () {
  27. alert('closed');
  28. }
  29. btn.onclick = function(){
  30. let val = input.value;
  31. if(!val){alert('消息不能为空!'); return false}
  32. ws.send(JSON.stringify({msg:val}));
  33. }
  34. close_btn.onclick = function(){
  35. ws.onclose = function(){
  36. console.log("Connection closed");
  37. }
  38. }
  39. ws.onerror = function (e) {
  40. alert("connecterror!");
  41. };
  42. }
  43. </script>
  44. </head>
  45. <body>
  46. <ul class="lists"></ul>
  47. <input type="text" class="input" />
  48. <button class="btn">发送</button>
  49. <button class="close">关闭</button>
  50. </body>
  51. </html>

客户端可以同时开始多个页面,都能同时获取到服务端的消息,因为在服务端已经做了循环处理

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/964006
推荐阅读
相关标签
  

闽ICP备14008679号