1.利用socket.io插件制作一个聊天框,原理是输入对话,发送到服务,服务器在返回相应的对话,最后插入页面中,时间对话的功能,这里我是使用的node.js搭建的服务器。

附上源码

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<textarea id="all" cols=40 rows=20></textarea>
<br />
<label>Message:</label>
<input id="message" type="text" name="message" cols=120/>
<input id="chat_btn" type="button" value="chat" onclick="chat_fn()" />
<label>NickName:</label>
<input id="nickname" typee="text" name="nickname" />
<input id="chang_name" type="button" value="nickname" onclick="change_nickname()" />
<!--<script src="../../../../npm/node_modules/socket.io/node_modules/socket.io-client/socket.io.js"></script>-->
<script src="http://localhost:8888/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8888');
socket.on("notice", function(data){
var msg = document.getElementById('all').value;
document.getElementById('all').innerText = msg + "\n" + data.message;
});
function chat_fn(){
var msg = document.getElementById("message").value;
socket.emit("chat", {message: msg});
};
var change_nickname = function(){
var nickname = document.getElementById("nickname").value;
socket.emit('setNickname',{nickname:nickname});
};
</script>
</body>
</html> 服务器代码
/**
* Created by on 2016/7/29.
*/
var app = require('http').createServer(handler)
, io = require('../../../../npm/node_modules/socket.io').listen(app)
, fs = require('fs');
app.listen(8888); function handler (req, res) {
fs.readFile('d://webstrom/yingtou/chart/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
console.log(err);
return res.end('Error loading index4.html');
}
res.writeHead(200);
res.end(data);
});
} io.sockets.on('connection', function (socket) {
socket.on("chat",function(data){
console.log(data);
socket.emit("notice", {message: ":" + data.message});
socket.broadcast.emit("notice", {message: ":" + data.message});
console.log("chat: " + data.message);
});
socket.on("setNickname",function(data){
socket.emit("notice", {message: ":" + data.nickname});
socket.broadcast.emit("notice", {message: ":" + data.nickname});
console.log("name:"+data.nickname)
})
});
05-07 15:41