您的位置:首页 > 其它

使用websocket的组件socket.io实现最简单的聊天室功能。

2016-06-06 00:00 991 查看
摘要: 使用websocket的组件socket.io实现最简单的聊天室功能。

参考这里:http://socket.io/get-started/chat/https://github.com/rauchg/chat-example

这里用到的目前流行的nodejs,它是以JavaScript为语言的一个平台,可以实现服务器功能。

创建项目目录,并安装组件。

[code=plain]npm install --save express@4.10.2
npm install --save socket.io

三个文件:

1 nodejs配置文件。

[code=plain]{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"express": "4.10.2",
"socket.io": "1.4.6"
}
}

2 服务器端代码文件。

[code=language-javascript]var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

//app.get('/', function(req, res){
//  res.send('<h1>Hello world</h1>');
//});

app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg){
console.log('message: ' + msg);
io.emit('chat message',socket.id+' : '+msg);
});
});

http.listen(3000, function(){
console.log('listening on *:3000');
});

3 客户端代码文件。

[code=language-html]<!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: .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 onload="alert('load')">
<h2>Hello, let's chat</h2>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript">
var socket = io();
$('form').submit(function(e){
//alert($('#m').val());
//alert('test');
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
</body>
</html>

这里的客户端文件要注意,<script>中的内容必须放到<form/>后面。当<script>中的内容放在<head>中时,JS脚本是不起作用的。

在服务器端运行node index.js即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: