We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
npm i express
// index.js // 创建一个 聊天的 IO const app = require('express')() const http = require('http').Server(app) const io = require('socket.io')(http) app.get('/', function (req, res) { res.sendFile(__dirname + '/index.html') }) io.on('connection', function (socket) { console.log('a user connection ....') socket.on('chat message', function (msg) { console.log('chat --- message' + msg) io.emit('chat message', msg) }) }) io.on('disconnect', function (req, res) { console.log('user disconnected') }) http.listen(3000, function () { console.log('服务已启动,端口 3000------') })
<!DOCTYPE html> <html> <head> <title>Socket.IO chat</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } body { font: 13px Helvetica, Arial; } form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; } form input { border: 0; padding: 10px; width: 90%; margin-right: 0.5%; } form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; } #messages { list-style-type: none; margin: 0; padding: 0; } #messages li { padding: 5px 10px; } #messages li:nth-child(odd) { background: #eee; } </style> </head> <body> <ul id="messages"></ul> <form action=""> <input id="m" autocomplete="off" /><button>Send</button> </form> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"> </script> <script src="http://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script> <script> $(function () { var socket = io(); $("form").submit(function (e) { e.preventDefault(); // 避免表单提交⾏行行为 socket.emit("chat message", $("#m").val()); $("#m").val(""); return false; }); socket.on("chat message", function (msg) { $("#messages").append($("<li>").text(msg)); }); }); </script> </body> </html>
ndoe index.js
socket.on
socket.emit
io.on
io.emit
参考资料:
The text was updated successfully, but these errors were encountered:
No branches or pull requests
准备
npm i express
ndoe index.js
启动项目,打开两个 浏览器 tab 进入同一个地址,即,输入消息的时候,2个窗口可以实现消息同步。注意几个问题:
socket.on
客户端的事件监听响应socket.emit
客户端派发监听事件io.on
服务端的事件监听响应io.emit
服务端派发监听事件参考资料:
The text was updated successfully, but these errors were encountered: