<p>如果我的客户端尝试连接一个不存在的服务端,那么就应该触发connect_failed这个事件。</p>
<p>官方文档上说是要加一个<code>connect timeout</code>的参数。但我加上之后还是没法触发这个事件。</p>
<p>客户端代码如下:</p>
<pre><code>var socket = io.connect(‘http://localhost:800’,{‘connect timeout’:5000}); var content = $(’#divcontent’);
socket.on('connecting',function(){
content.append($('<p>').text('Connecting'));
});
socket.on('connect_failed',function(){
content.append($('<p>').text('Failed to connect'));
});
socket.on('connect',function(){
content.append($('<p>').text('Connected'));
});
</code></pre>
<p>还有什么其他要注意的地方么?</p>
给你提供点儿线索,我是这样写的: var socket = new io.Socket(“localhost”, { port: 8000 }); socket.connect(); socket.on(“connect”, function(){ console.log(“connected”); }); socket.on(“message”, function(data){ console.log("received message: " + data); document.getElementById(“message”).innerHTML = data; }); socket.on(“disconnect”, function(){ console.log(“disconnected”); })
@Pursuer 用你这种写法试了下,貌似连正常的连接都连不上。
我的服务端是这样写的:
var http= require("http"),
io = require("socket.io");
//create HTTP server var server = http.createServer(function(request,response){ response.writeHead({“Content-Type”:“text/html”}); response.end(“HTML5 WebSocket Demo”); });
server.listen(8000,“localhost”);
//Wrap HTTP server by socket.io var socket = io.listen(server); socket.on(“connection”,function(client){ console.log(“connected”); client.on(“message”,function(data){ client.packet(“Hello”+data); }); client.on(“disconnect”,function(){ console.log(“disconnected”); }); });