socket.io实现

时间:2023-12-31 22:18:26

后台代码 index_server.js

var app = require('http').createServer(handler)//创建服务器app
, io = require('socket.io').listen(app)//引用socket.io模块监听app
, fs = require('fs')//引用文件处理模块 app.listen(80);//指定app监听的端口,第二个参数127.0.0.1可省略 function handler (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.end(data);
});
} io.sockets.on('connection', function (socket) {//当客户端connection的时候,调用函数function (socket)
socket.emit('news', { hello: 'link is OK' });//连接成功后发送news消息,传递一个josn对象
socket.on('content', function (data) {//服务端发送my other event时,服务器接收后执行后面的函数
socket.emit('content_callback', data);
});
});

前端代码 index.html

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body style="margin:0 auto;padding:0px;">
<center>
请输入你的名字:<input id="username" type="text" value="" name="username"/>
<input type="button" onclick="create_user()" value="提交"/><br />
<input type="text" value="" name="content"/>
<input id="content" onclick="send()" type="button" value="发送"/><br />
<span id="link"></span><br/>
<textarea name="" id="text" cols="120" rows="20"></textarea>
</center>
</body>
<script type="text/javascript" src="/socket.io/socket.io.js"></script> <script type="text/javascript">
var user="";
var socket = io.connect('http://localhost');//创建本地sock连接
socket.on('news',function (data) {//Socket接收news消息时执行回调函数
var lable=document.getElementById("link");
lable.innerHTML =data.hello;
});
socket.on('content_callback',function (data) {//Socket接收news消息时执行回调函数
var textarea=document.getElementById("text");
text.value =data["user"]+"\n"+data["content"]; var json = eval(data);
console.log(data);
});
function create_user(){
var username=document.getElementById("username");
if(username.value=="" || username.value==null){
alert("输入为空!");
return;
}
user=username.value;
username.disabled=true;
alert("你的用户名为:"+user); }
function send () {
var chat={user:user,};
var content=document.getElementById("content");
if(content.value=="" || content.value==null){
alert("请输入你要发送的内容");
return;
}
chat['content'] = content.value;
socket.emit('content',chat);
}
</script>
</html>