index.js
socket: a socket declared in client, and it's listening to client event
io: this is the server
(msg from index.html to index.js, and then to index.js)
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
io.on('connection', (socket) => {
console.log('user connected');
socket.on('message', (msg) => {
console.log(`message from client (html file): ${msg}`);
io.emit('message', `Re-emitted ${msg} from server`);
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chatter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<style>
form { padding: 20px; position: fixed; bottom: 0; width: 100%; padding-right: 50px;}
#messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee;}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<ul id="messages"></ul>
</div>
<div class="row">
<div class="col-lg-6">
<form action="">
<div class="input-group">
<input id="m" autocomplete="off" type="text" class="form-control" placeholder="Message..." aria-label="Message...">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
$('form').submit(() => {
socket.emit('message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('message', (msg) => {
$('#messages').append($('<li>').text(msg));
})
</script>
</body>
</html>
socket connect and disconnect
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
io.on('connection', (socket) => {
console.log('user connected');
socket.on('message', (msg) => {
console.log(`message: ${msg}`);
io.emit('message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
io.emit('message', 'user disconnected');
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chatter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<style>
form { padding: 20px; position: fixed; bottom: 0; width: 100%; padding-right: 50px;}
#messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee;}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<ul id="messages"></ul>
</div>
<div class="row">
<div class="col-lg-6">
<form action="">
<div class="input-group">
<input id="m" autocomplete="off" type="text" class="form-control" placeholder="Message..." aria-label="Message...">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
$('form').submit(() => {
socket.emit('message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('connect', () => {
// emiting to everybody
socket.emit('message', 'user connected');
})
socket.on('message', (msg) => {
$('#messages').append($('<li>').text(msg));
})
</script>
</body>
</html>
namespace
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// tech namespace
const tech = io.of('/tech');
tech.on('connection', (socket) => {
console.log('user connected');
socket.on('message', (msg) => {
console.log(`message: ${msg}`);
tech.emit('message', msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
tech.emit('message', 'user disconnected');
})
})
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chatter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<style>
form { padding: 20px; position: fixed; bottom: 0; width: 100%; padding-right: 50px;}
#messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee;}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<ul id="messages"></ul>
</div>
<div class="row">
<div class="col-lg-6">
<form action="">
<div class="input-group">
<input id="m" autocomplete="off" type="text" class="form-control" placeholder="Message..." aria-label="Message...">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('/tech');
$('form').submit(() => {
socket.emit('message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('connect', () => {
// emiting to everybody
socket.emit('message', 'user connected');
})
socket.on('message', (msg) => {
$('#messages').append($('<li>').text(msg));
})
</script>
</body>
</html>
chat room
index.js
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = 3000;
server.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/public/index.html');
});
// tech namespace
const tech = io.of('/tech');
tech.on('connection', (socket) => {
socket.on('join', (data) => {
socket.join(data.room);
tech.in(data.room).emit('message', `New user joined ${data.room} room!`);
})
socket.on('message', (data) => {
console.log(`message: ${data.msg}`);
tech.in(data.room).emit('message', data.msg);
});
socket.on('disconnect', () => {
console.log('user disconnected');
tech.emit('message', 'user disconnected');
})
})
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chatter</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<style>
form { padding: 20px; position: fixed; bottom: 0; width: 100%; padding-right: 50px;}
#messages { list-style-type: none; margin: 0; padding: 0; width: 100%;}
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee;}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<ul id="messages"></ul>
</div>
<div class="row">
<div class="col-lg-6">
<form action="">
<div class="input-group">
<input id="m" autocomplete="off" type="text" class="form-control" placeholder="Message..." aria-label="Message...">
<span class="input-group-btn">
<button class="btn btn-secondary" type="submit">Send</button>
</span>
</div>
</form>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
const room = 'javascript';
const socket = io('/tech');
$('form').submit(() => {
let msg = $('#m').val();
socket.emit('message', { msg, room });
$('#m').val('');
return false;
});
socket.on('connect', () => {
// emiting to everybody
socket.emit('join', { room: room });
})
socket.on('message', (msg) => {
$('#messages').append($('<li>').text(msg));
})
</script>
</body>
</html>
debug

{
"name": "chatter",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon ./index.js --exec babel-node -e js",
"test": "DEBUG=* nodemon ./index.js --exec babel-node -e js"
},
"author": "Emmanuel Henri",
"license": "ISC",
"dependencies": {
"express": "^4.16.2",
"nodemon": "^1.12.1",
"socket.io": "^2.0.3"
},
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.6.0",
"babel-preset-stage-0": "^6.24.1"
}
}

npm run test
https://socket.io/docs/emit-cheatsheet/
https://socket.io/docs/server-api/
https://socket.io/docs/client-api/

1612

被折叠的 条评论
为什么被折叠?



