前端代码:
<!doctype html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
html,
body {
width: 100%;
height: 100%;
}
#box {
position: absolute;
bottom: 0;
}
</style>
</head>
<body>
<ul id="message-box"></ul>
<div id="box">
<input id="edit-box" autocomplete="off" /><button id="btn">Send</button>
</div>
<script src="socket.io.js"></script>
<script>
var socket = io();
document.getElementById('btn').onclick = function () {
socket.emit('message', document.getElementById('edit-box').value);
document.getElementById('edit-box').value = '';
};
socket.on('message', function (message) {
var li = document.createElement('li');
li.innerHTML = message;
document.getElementById('message-box').appendChild(li);
});
</script>
</body>
</html>
后端代码:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var path = require('path');
app.use(express.static(__dirname));
app.get('/', function (request, response) {
response.sendFile(path.join(__dirname, 'index.html'));
});
io.on('connection', function (socket) {
console.log('a user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
socket.on('message', function (message) {
console.log('message: ' + message);
io.emit('message', message);
});
});
var server = http.listen(4000, function () {
console.log('Sever is running');
});