赞
踩
- var wsServer = require("ws").Server;
- var ws = new wsServer({port:3000});
-
-
- var clientArr = [];
- var i = 0;
- ws.on("connection",function(client){
- console.log("aaa");
- clientArr.push(client);
- // client.id = i ++;
- client.on("message",function(data){
- clientArr.map(function(item){
- // console.log(JSON.stringify(data))
- item.send(data);
- })
- })
- })
以上是服务器部署代码.
- //var wsClient = new WebSocket("ws://127.0.0.1:3000");
- //var wsClient = new WebSocket("ws://10.8.158.21:3000");
- var wsClient = new WebSocket("ws://echo.websocket.org");
-
- wsClient.onmessage = function(evt){
- console.log("aaa");
- var obj = JSON.parse(evt.data);
- console.log(evt.data);
- $("#box").append(`<p>${obj.id}说:${obj.data}</p>`);
- }
- $("#btn").click(function(){
- var obj = {};
-
- console.log(wsClient);
- console.log(wsClient.readyState);
- if(wsClient.readyState==1){
- obj.id = "李杰";
- obj.data = $("#txt").val();
- wsClient.send(JSON.stringify(obj));
- }
-
- })
以上是客户端部署代码.
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。