zoukankan      html  css  js  c++  java
  • 使用socket.io实现简单的聊天功能

    Socket.io实际上是WebSocket的父集,Socket.io封装了WebSocket和轮询等方法

    首先得在你的项目中安装socket.io

    $ npm install socket.io

    服务端代码:

    var app=require('http').createServer()
    var io=require('socket.io')(app)
    var PORT =5555;
    var clientCount=0;
    
    app.listen(PORT)
    
    io.on('connection',function(socket){
        clientCount++
        socket.nickname='user'+clientCount
        io.emit('enter',socket.nickname+' comes in')
    
        socket.on('message',function(str){
            io.emit('message',socket.nickname+' says: '+str)
        })
    
        socket.on('disconnect',function(){
            io.emit('leave',socket.nickname+' left')
        })
    })

    客户端代码:

    <!DOCTYPE html>
    <html>
    <head>
        <mate charset='utf-8' />
        <title>websocket</title>
        <script src="socket.io.js"></script>
    </head>
    <body>
        
        <h1>chat room</h1>
        <input type="text" id='sendtxt' />
        <button id='sendbtn'>发送</button>
        <div id="recv"></div>
        <script type="text/javascript">
            var socket=io("ws://localhost:5555/");
    
            function showMessage(str,type){
                var div=document.createElement('div');
                div.innerHTML=str;
                if(type=='enter'){
                    div.style.color='blue';
                }else if(type=='leave'){
                    div.style.color='red'
                }
                document.body.appendChild(div);
            }
    
            document.getElementById('sendbtn').onclick=function(){
                var txt=document.getElementById("sendtxt").value;
                if(txt){
                    socket.emit('message',txt);
                }
            }
    
            socket.on('enter',function(data){
                showMessage(data,'enter')
            })
    
            socket.on('message',function(data){
                showMessage(data,'message')
            })
    
            socket.on('leave',function(data){
                showMessage(data,'leave')
            })
            
        </script>
    </body>
    </html>

    来自慕课网课程:

    https://www.imooc.com/learn/861

  • 相关阅读:
    Codeforces #548 (Div2)
    Codeforces #550 (Div3)
    UVA
    ios 动画
    CAAnimation
    iOS三种定时器的用法NSTimer、CADisplayLink、GCD
    iOS使用宏写单例
    iOS完美的网络状态判断工具
    iOS开发
    iOS自定义控件教程:制作一个可重用的旋钮
  • 原文地址:https://www.cnblogs.com/qiufang/p/8610438.html
Copyright © 2011-2022 走看看