Node.js笔记(四)局域网聊天室2:服务端接受客户端消息

目标

客户端服务端建立连接加载,服务端能接受客户端传过来的消息

代码

  • JS部分<chatroom.js>
javascript 复制代码
const express = require('express')
const http = require('http')
const {Server} = require('socket.io')

const app = express()
const server = http.createServer(app)
const io = new Server(server)

app.use(express.static(__dirname))
io.on('connect',(socket)=>{
    console.log('an user connected')
    \\监听客户端的信息,注意函数的第一个事件参数名要与Html部分里的事件名保持一致
    socket.on('chat message',(msg)=>{
        console.log('Message received:',msg)
    })
    socket.on('disconnect',()=>{
        console.log("an user disconnected")
    })
}
    
)

const port =3001
server.listen(port,()=>{
    console.log(`server is running at http://localhost:${port}`)
})

socket.on()的第一个参数是事件名,事件名有一些是库里预先定好的可以比如connectdisconnect等,其他的都可以自己定义。同时非常关键的一点,如果是想让htmljs产生互动,就必须保持事件名的一致性

  • Html部分<index.html>
html 复制代码
<!DOCTYPE html>
<html>
    <head>
        <script src="/socket.io/socket.io.js"></script>
    </head>
    <body>
        <h1>Chat Room</h1>
        <input id="inputtext" placeholder="Enter your message">
        <button id="sendbtn">Send</button>
        <script>
            const socket = io()
            const input = document.getElementById('inputtext')
            const sendbtn = document.getElementById('sendbtn')
            sendbtn.addEventListener("click",()=>{
                const message = input.value
                if(message){
                    socket.emit("chat message",message)
                    input.value=''
                }
            })
            socket.on('chat message',(msg)>{

            })
        </script>
    </body>
</html>

效果

  • JS部分<chatroom.js>

  • Html部分<index.html>

相关推荐
新子y8 分钟前
【小白笔记】最大交换 (Maximum Swap)问题
笔记·python
你要飞4 小时前
Hexo + Butterfly 博客添加 Live2D 看板娘指南
笔记
哆啦A梦15886 小时前
搜索页面布局
前端·vue.js·node.js
Q_Q5110082857 小时前
python+uniapp基于微信小程序的旅游信息系统
spring boot·python·微信小程序·django·flask·uni-app·node.js
ajsbxi7 小时前
【Java 基础】核心知识点梳理
java·开发语言·笔记
哆啦A梦15887 小时前
axios 的二次封装
前端·vue.js·node.js
呱呱巨基7 小时前
vim编辑器
linux·笔记·学习·编辑器·vim
Q_Q5110082857 小时前
python基于web的汽车班车车票管理系统/火车票预订系统/高铁预定系统 可在线选座
spring boot·python·django·flask·node.js·汽车·php
新子y8 小时前
【小白笔记】普通二叉树(General Binary Tree)和二叉搜索树的最近公共祖先(LCA)
开发语言·笔记·python
聪明的笨猪猪8 小时前
Java JVM “调优” 面试清单(含超通俗生活案例与深度理解)
java·经验分享·笔记·面试