码迷,mamicode.com
首页 > Web开发 > 详细

web通信技术之websocket

时间:2017-10-12 14:36:26      阅读:289      评论:0      收藏:0      [点我收藏+]

标签:style   tin   interval   des   class   http   sock   logs   gettime   

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

标签:style   tin   interval   des   class   http   sock   logs   gettime   

原文地址:http://www.cnblogs.com/hellohello/p/7655893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!