1. 程式人生 > >web通信技術之websocket

web通信技術之websocket

spa list int socket例子 .com class srv utf from

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