後臺代碼 index_server.jsjavascript
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.htmlhtml
<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>