使用socket.io实现简单的聊天功能

本文介绍如何使用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

转载于:https://www.cnblogs.com/qiufang/p/8610438.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值