Nodejs实现WebSocket
来源:互联网 发布:java web 中文乱码 编辑:程序博客网 时间:2024/05/22 13:55
1.nodejs服务端开启socket服务:
var ws = require('nodejs-websocket');console.log('开始建立连接...')ws.createServer(function (conn) { conn.on('text', function (str) { console.log('收到的信息为:' + str) conn.sendText(str) }) conn.on('close', function (code, reason) { console.log('关闭连接', code, reason) }); conn.on('error', function (code, reason) { console.log('异常关闭', code, reason) });}).listen(8001)console.log('WebSocket建立完毕');
2.html5端测试程序:
<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" /> <title>WebSocket</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"> <link href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> <style> body{ width: 96%; margin-left: 2%; margin-top: 20px; } </style></head><body><div class="btn-group box" role="group" aria-label="..."> <button type="button" class="btn btn-default">Oppo</button> <button type="button" class="btn btn-default">Vivo</button> <button type="button" class="btn btn-default">Apple</button></div><div class="page-header"> <h5 class="info">服务器返回信息列表:</br></br></h5></div><script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script><script src="https://cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script><script> if (window.WebSocket) { var ws = new WebSocket('ws://127.0.0.1:8001'); ws.onopen = function () { console.log('连接服务器成功!'); ws.send('startting...'); } ws.onclose = function () { console.log('服务器关闭'); } ws.onerror = function () { console.log("连接出错"); } ws.onmessage = function (e) { document.querySelector(".box").onclick = function (e) { ws.send('当前点击框的内容为:<font style="color:red;" >' + e.target.innerHTML+'</font>'); } $('.info').append(e.data + '</br></br>'); } }</script></body></html>
阅读全文
0 0
- nodejs+nodejs-websocket 实现websocket
- Nodejs实现WebSocket
- HTML5 WebSocket + NodeJs 实现聊天室
- HTML5+NodeJs实现WebSocket即时通讯
- HTML5+NodeJs实现WebSocket即时通讯
- HTML网页+nodejs实现websocket
- HTML5+NodeJs实现WebSocket即时通讯
- Nodejs实现websocket的4种方式
- NodeJS实现WebSocket,太容易了吧!!
- NodeJs WS 模块 实现 WebSocket 聊天
- nodejs+socket.io实现websocket通信初探
- Nodejs实现websocket的4种方式
- nodejs+express+websocket+redis实现消息订阅系统
- NodeJS+Expres+Socket.io实现HTTP通知websocket客户端
- 浅析nodejs实现Websocket的数据接收与发送
- 浅析nodejs实现Websocket的数据接收与发送
- 用nodejs快速实现微信小程序的websocket服务端
- NodeJS实现WebSocket前端和服务器通信,实时推送
- pyspider中内容选择器常用方法汇总
- 逻辑回归(Logistic Regression)
- [刷题]Codeforces Round #389(Div. 2)
- 多个 ul / ol (无序列表/有序列表)的嵌套时的重叠问题
- 杭电2018母牛的故事
- Nodejs实现WebSocket
- C语言:break和continue语句改变循环
- 列表生成式
- 启动projectname-servlet.xml
- git merge简介
- 驻极体麦和MEMS麦
- SVM 分类算法
- PHP非递归方式实现无限分类(转载)
- A poem