Nodejs实现WebSocket
2017-07-12 15:56
169 查看
1.nodejs服务端开启socket服务:
2.html5端测试程序:
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>
相关文章推荐
- HTML5+NodeJs实现WebSocket即时通讯
- HTML5+NodeJs实现WebSocket即时通讯
- Nodejs实现websocket的4种方式
- nodejs基于WS模块实现WebSocket聊天功能的方法
- HTML网页+nodejs实现websocket
- 记websocket(windows系统下nodejs,node-websocket-server实现简单聊天)
- 用nodejs快速实现微信小程序的websocket服务端
- NodeJS简单实现WebSocket功能示例
- HTML5+NodeJs实现WebSocket即时通讯
- 浅析nodejs实现Websocket的数据接收与发送
- 基于html5和nodejs相结合实现websocket即使通讯
- HTML5+NodeJs实现WebSocket即时通讯
- NodeJS实现WebSocket,太容易了吧!!
- Nodejs实现websocket的4种方式
- HTML5+NodeJs实现WebSocket即时通讯
- 基于html5和nodejs相结合实现websocket即使通讯
- nodejs--websocket简易代码实现局域网多个客户端进行通信
- 浅析nodejs实现Websocket的数据接收与发送
- NodeJS实现WebSocket前端和服务器通信,实时推送