node.js中ws模块创建服务端和客户端,网页WebSocket客户端
首先下载websocket模块,命令行输入
npm install ws
1.node.js中ws模块创建服务端
// 加载node上websocket模块 ws;
var ws = require("ws");
// 启动基于websocket的服务器,监听我们的客户端接入进来。
var server = new ws.Server({
host: "127.0.0.1",
port: 6080,
});
// 监听接入进来的客户端事件
function websocket_add_listener(client_sock) {
// close事件
client_sock.on("close", function() {
console.log("client close");
});
// error事件
client_sock.on("error", function(err) {
console.log("client error", err);
});
// end
// message 事件, data已经是根据websocket协议解码开来的原始数据;
// websocket底层有数据包的封包协议,所以,绝对不会出现粘包的情况。
// 每解一个数据包,就会触发一个message事件;
// 不会出现粘包的情况,send一次,就会把send的数据独立封包。
// 如果我们是直接基于TCP,我们要自己实现类似于websocket封包协议就可以完全达到一样的效果;
client_sock.on("message", function(data) {
console.log(data);
client_sock.send("Thank you!");
});
// end
}
// connection 事件, 有客户端接入进来;
function on_server_client_comming (client_sock) {
console.log("client comming");
websocket_add_listener(client_sock);
}
server.on("connection", on_server_client_comming);
// error事件,表示的我们监听错误;
function on_server_listen_error(err) {
}
server.on("error", on_server_listen_error);
// headers事件, 回给客户端的字符。
function on_server_headers(data) {
// console.log(data);
}
server.on("headers", on_server_headers);2.node.js中ws模块创建客户端
var ws = require("ws");
// url ws://127.0.0.1:6080
// 创建了一个客户端的socket,然后让这个客户端去连接服务器的socket
var sock = new ws("ws://127.0.0.1:6080");
sock.on("open", function () {
console.log("connect success !!!!");
sock.send("HelloWorld1");
sock.send("HelloWorld2");
sock.send("HelloWorld3");
sock.send("HelloWorld4");
sock.send(Buffer.alloc(10));
});
sock.on("error", function(err) {
console.log("error: ", err);
});
sock.on("close", function() {
console.log("close");
});
sock.on("message", function(data) {
console.log(data);
});3.网页客户端创建(使用WebApi --->WebSocket)
<!DOCTYPE html>
<html>
<head>
<title>skynet websocket example</title>
</head>
<body>
<script>
var ws = new WebSocket("ws://127.0.0.1:6080/index.html");
ws.onopen = function(){
alert("open");
ws.send("WebSocket hellowrold!!");
};
ws.onmessage = function(ev){
alert(ev.data);
};
ws.onclose = function(ev){
alert("close");
};
ws.onerror = function(ev){
console.log(ev);
alert("error");
};
</script>
</body>
</html>以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对安科网的支持。如果你想了解更多相关内容请查看下面相关链接
相关推荐
firejq 2020-06-14
woniyu 2020-06-02
取个好名字真难 2020-06-01
woniyu 2020-05-20
darylove 2020-05-14
shufen0 2020-04-18
shufen0 2020-04-14
guozewei0 2020-03-06
取个好名字真难 2020-02-13
柳木木的IT 2020-11-04
joynet00 2020-09-23
wenf00 2020-09-14
蓝色深海 2020-08-16
wuychn 2020-08-16
取个好名字真难 2020-08-06
darylove 2020-06-26
shufen0 2020-06-20
Lovexinyang 2020-06-14