当前位置:   article > 正文

websocket_ws = new websocket

ws = new websocket
  1. var wsServer = require("ws").Server;
  2. var ws = new wsServer({port:3000});
  3. var clientArr = [];
  4. var i = 0;
  5. ws.on("connection",function(client){
  6. console.log("aaa");
  7. clientArr.push(client);
  8. // client.id = i ++;
  9. client.on("message",function(data){
  10. clientArr.map(function(item){
  11. // console.log(JSON.stringify(data))
  12. item.send(data);
  13. })
  14. })
  15. })

以上是服务器部署代码.

  1. //var wsClient = new WebSocket("ws://127.0.0.1:3000");
  2. //var wsClient = new WebSocket("ws://10.8.158.21:3000");
  3. var wsClient = new WebSocket("ws://echo.websocket.org");
  4. wsClient.onmessage = function(evt){
  5. console.log("aaa");
  6. var obj = JSON.parse(evt.data);
  7. console.log(evt.data);
  8. $("#box").append(`<p>${obj.id}说:${obj.data}</p>`);
  9. }
  10. $("#btn").click(function(){
  11. var obj = {};
  12. console.log(wsClient);
  13. console.log(wsClient.readyState);
  14. if(wsClient.readyState==1){
  15. obj.id = "李杰";
  16. obj.data = $("#txt").val();
  17. wsClient.send(JSON.stringify(obj));
  18. }
  19. })
以上是客户端部署代码.


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

闽ICP备14008679号