web通信技术之websocket
Posted HelloHello233
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web通信技术之websocket相关的知识,希望对你有一定的参考价值。
websocket例子:
client
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.bootcss.com/socket.io/1.7.2/socket.io.js"></script> <body> <script> var socket = io.connect(‘http://127.0.0.1:8080‘); socket.on(‘connect‘,function() { console.log(‘Client has connected to the server!‘); sendMessageToServer(‘hello,now is connected‘); }); socket.on(‘message‘,function(data) { console.log(‘Received a message from the server!‘,data); }); socket.on(‘disconnect‘,function() { console.log(‘The client has disconnected!‘); }); function sendMessageToServer(message) { socket.send(message); } </script> </body> </html>
nodeSrv
var http= require(‘http‘), io= require(‘socket.io‘); var server= http.createServer(function(req, res){ res.end(‘<h1>will see this in http://localhost:8080</h1>‘); }); server.listen(8080); var socket= io.listen(server); socket.on(‘connection‘, function(client){ var interval= setInterval(function() { client.send(‘This is a message from the server! ‘ + new Date().getTime()); },5000); client.on(‘message‘,function(event){ console.log(‘Received message from client!‘,event); }); client.on(‘disconnect‘,function(){ clearInterval(interval); console.log(‘Server has disconnected‘); }); });
以上是关于web通信技术之websocket的主要内容,如果未能解决你的问题,请参考以下文章
基于go-gin框架的web服务框架之websocket(二)