1、首先安装好nodejs-websocket
npm install nodejs-websocket --save -g
2、编写服务端
var ws = require(\"nodejs-websocket\")
var AllUserData = new Array()
// Scream server example: \"hi\" -> \"HI!!!\"
var server = ws.createServer(function (conn) {
console.log(\"New connection\")
conn.on(\"text\", function (str) {
console.log(\"Received \"+str)
AllUserData.push({
\'id\':str,
\'ws\':conn
})
conn.sendText(str.toUpperCase()+\"!!!\")
})
conn.on(\"close\", function (code, reason) {
console.log(\"Connection closed\")
// 当用户退出的时候捕捉到退出的用户
for (var i=0 in AllUserData) {
if (AllUserData[i].ws == conn) {
console.log(AllUserData[i])
}
}
})
}).listen(8001)
3、简易客户端
<!DOCTYPE html>
<html>
<head>
< >django-websocket</ >
< src=\"http://code.jquery.com/jquery-1.11.1.min.js\"></ >
< type=\"text/ \">//<![CDATA[
$(function () {
$(\'#connect_websocket\').click(function () {
if (window.s) {
window.s.close()
}
/*创建socket连接*/
var socket = new WebSocket(\"ws://127.0.0.1:8001\");
socket.onopen = function () {
console.log(\'WebSocket open\');//成功连接上Websocket
};
socket.onmessage = function (e) {
console.log(\'message: \' + e.data);//打印出服务端返回过来的数据
$(\'#messagecontainer\').prepend(\'<p>\' + e.data + \'</p>\');
};
// Call onopen directly if socket is already open
if (socket.readyState == WebSocket.OPEN) socket.onopen();
window.s = socket;
});
$(\'#send_message\').click(function () {
//如果未连接到websocket
if (!window.s) {
alert(\"websocket未连接.\");
} else {
window.s.send($(\'#message\').val());//通过websocket发送数据
}
});
$(\'#close_websocket\').click(function () {
if (window.s) {
window.s.close();//关闭websocket
console.log(\'websocket已关闭\');
}
});
});
//]]></ >
</head>
<body>
<br>
<input type=\"text\" id=\"message\" value=\"user1\"/>
<button type=\"button\" id=\"connect_websocket\">连接 websocket</button>
<button type=\"button\" id=\"send_message\">发送 message</button>
<button type=\"button\" id=\"close_websocket\">关闭 websocket</button>
<h1>Received Messages</h1>
<div id=\"messagecontainer\">
</div>
</body>
</html>
总结
以上所述是小编给大家介绍的nodejs 使用nodejs-websocket模块实现点对点实时通讯,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
继续阅读与本文标签相同的文章
下一篇 :
Facebook F8 遥望笔记
-
[译] React 中的调度
2026-05-19栏目: 教程
-
[译] 编写可以复用的 HTML 模板
2026-05-19栏目: 教程
-
项目的自述文档(README)模板
2026-05-19栏目: 教程
-
[Spring Cloud Tutorial翻译系列二]Spring Cloud Config Server与git集成
2026-05-19栏目: 教程
-
[译] 在 iOS Swift 中的懒加载变量
2026-05-19栏目: 教程
