首页 > Web开发 > 详细

web通信技术之websocket

时间:2017-10-12 14:27:32      阅读:237      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!