首页 / 操作系统 / Linux / WebSocket实例-Node.js和Socket.IO
费话就不多说了,先来说一个WebSocket的环境配置,用的是node.js和Socket.IO。首先需要安装node.js,很简单。下载node.js,下载完成后双击安装,CMD打开命令窗口,指定到nodejs的安装目录。安装Socket.IO也很容易,一条语包搞定,npm install socket.io,等待安装完成就可以在nodejs安装目录下,新建http.js(文件名任取),代码如下:var fs = require("fs")
, http = require("http")
, socketio = require("socket.io");
var server = http.createServer(function(req, res) {
res.writeHead(200, { "Content-type": "text/html"});
res.end(fs.readFileSync(__dirname + "/index.html"));
}).listen(8888, function() {
console.log("Listening at: http://localhost:8888");
});
socketio.listen(server).on("connection", function (socket) {
socket.on("message", function (msg) {
console.log("Message Received: ", msg);
socket.broadcast.emit("message", msg);
});
});再新建一个index.html,代码如下:<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$(function(){
var iosocket = io.connect();
iosocket.on("connect", function () {
$("#incomingChatMessages").append($("<li>Connected</li>"));
iosocket.on("message", function(message) {
$("#incomingChatMessages").append($("<li></li>").text(message));
});
iosocket.on("disconnect", function() {
$("#incomingChatMessages").append("<li>Disconnected</li>");
});
});
$("#outgoingChatMessage").keypress(function(event) {
if(event.which == 13) {
event.preventDefault();
iosocket.send($("#outgoingChatMessage").val());
//$("#incomingChatMessages").append($("<li></li>").text($("#outgoingChatMessage").val()));
$("#outgoingChatMessage").val("");
}
});
});
</script>
</head>
<body>
Incoming Chat: <ul id="incomingChatMessages"></ul>
<br />
<input type="text" id="outgoingChatMessage">
</body>
</html>到此,所有的代码部分都已经完成,接下来就是运行了,在命令窗口中,切换到nodejs的安装目录,运行如下指令:>node http.js,效果如下图现在我们运行两个浏览器(必须支持websocket的)就可以相互发消息了,效果图下图相关阅读:Node.js+socket.io+聊天室源码 http://www.linuxidc.com/Linux/2013-10/91617.htmNode.js 的详细介绍:请点这里
Node.js 的下载地址:请点这里推荐阅读:Node.Js入门[PDF+相关代码] http://www.linuxidc.com/Linux/2013-06/85462.htmNode.js安装与配置 http://www.linuxidc.com/Linux/2013-05/84836.htmSocket.IO 和 Node.js 入门 http://www.linuxidc.com/Linux/2012-05/60447.htm使用HTML5,WebSockets,nodejs和socket.io构建实时游戏 http://www.linuxidc.com/Linux/2012-06/61798.htm