先npm安装websocket
websocket全双工通讯协议tcp(一直保持着长连接)
http是一个无状态的无连接,单向的应用层协议,采用了请求/响应模式,通讯请求只能由客户端发起,服务端应答,无法实现主动向客户端发起消息,
先new一个websocket(参数:用户参数和url组成一个新的url)。open是与服务器建立连接,onmessage是接收后端发过来的数据,send(value)客户端发送数据
npm install websocket
nodejs中server.js
var WebSocketServer = require('websocket').server;//引入模块
var http = require('http');//需要底层的http模块
//创建服务器
var server = http.createServer(function(request, response) {
console.log((new Date()) + ' Received request for ' + request.url);
response.writeHead(404);
response.end();
});
//监听3000端口
server.listen(3000, function() {
console.log((new Date()) + ' Server is listening on port 3000');
});
//创建websocket服务器对象
wsServer = new WebSocketServer({
httpServer: server,//配置刚刚创建的服务器
});
//websocket建立连接
wsServer.on('request', function(request) {
//当前的连接 使用子协议
// var connection = request.accept('echo-protocol', request.origin);
var connection = request.accept(null, request.origin);//没有直接null
connection.sendUTF('信息')//发送信息到客户端
connection.on('message',function (msg) {
connection.sendUTF(msg.utf8Data)
})
});
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
//创建websocket对象
var socket=new WebSocket('ws://localhost:3000');
//监听建立连接
socket.onopen=function (res) {
console.log('连接成功')
console.log(res)
}
//监听消息
socket.onmessage=function (data) {
console.log('有消息来了')
console.log(data.data)
}
function sendmsg(){
var a=document.getElementById('inputid').value;
socket.send(a)
}
</script>
</head>
<body>
<input type="text"id="inputid">
<input type="button"value="发送" onclick="sendmsg()">
</body>
</html>