$ npm init
$ cat package.json
{
"name": "chatroom",
"version": "1.0.0",
"description": "a room which lets people chat",
"main": "index.js",
"scripts": {
"test": "nothing"
},
"author": "voidy",
"license": "ISC",
}
$ npm install socket.io --save
"dependencies": {
"socket.io": "^1.2.1"
}
var http = require('http');
var socketio = require('socket.io');
var fs = require('fs');
var app = http.createServer(function(req, res) {
fs.readFile(__dirname + '/index.html', function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.write(data);
res.end();
});
}).listen(8888);
var io = socketio(app);
io.on('connection', function (socket) {
// 监听浏览器端的chat事件
socket.on('chat', function (data) {
console.log(data);
io.emit('sendmsg', data);
});
});
console.log("Server is running at http://localhost:8888")
<html>
<head>
<meta charset="utf-8">
<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: .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>
<!-- 引入socket.io库和jQuery库 -->
<script src="https://cdn.socket.io/socket.io-1.2.1.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<!-- 显示消息记录 -->
<ul id="messages"></ul>
<!-- 消息发送框 -->
<div id="form">
<input id="m" autocomplete="off" /><button id="send">Send</button>
</div>
</body>
</html>
<script>
// 连接到Socket.IO服务器
var socket = io.connect();
$(function() {
// 绑定发按钮发送消息的事件
$('#send').on('click', function() {
var data = $('#m').val();
// 创建chat事件并发送消息给服务器
// emit('event') 表示发送了一个event命令
// 使用io.on('event')接收对应事件的信息
// 所以客户端服务器端需要使用socket.on('chat')接收聊天信息
socket.emit('chat', { msg: data });
$('#m').val('');
});
});
$(function() {
// 接收消息并显示到消息记录框中
socket.on('sendmsg', function(msg) {
$('#messages').append($('<li>').text(msg.msg));
});
});
</script>
$ node index.js
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有