Giải pháp này, dựa trên công trình của Jujuler. Rõ ràng trong socket.io 1.0, nó là "forceNew" thay vì "force new connection" - cả hai đều hoạt động.
Server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('s.html');
});
io.on('connection', function(socket){
console.log('a user connected: ' + socket.id);
socket.on('disconnect', function(){
console.log(socket.name + ' has disconnected from the chat.' + socket.id);
});
socket.on('join', function (name) {
socket.name = name;
console.log(socket.name + ' joined the chat.');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Khách hàng (s.html):
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>button{width: 100px;}input{width: 300px;}</style>
</head>
<body>
<ul id="messages"></ul>
<button id="disconnect">disconnect</button>
<button id="connect">connect</button>
<script src="/socket.io/socket.io.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
$('#disconnect').click(function(){
socket.disconnect();
});
$('#connect').click(function(){
// socket.socket.reconnect();
// socket = io.connect('http://localhost:3000',{'force new connection':true });
socket = io.connect('http://localhost:3000',{'forceNew':true });
socket.on('connect', function(msg){
socket.emit('join', prompt('your name?'));
});
});
socket.on('connect', function(msg){
socket.emit('join', prompt('your name?'));
});
socket.on("disconnect", function(){
console.log("client disconnected from server");
});
</script>
</body>
</html>
Nguồn
2014-07-07 16:28:23
dụ của bạn làm việc cho tôi. – vinayr
nó hoạt động một lần. nhưng nó có hoạt động nhiều lần không? Nó không dành cho tôi. Tôi đã đoán những thay đổi socket.id và sau đó ngắt kết nối không còn kết hợp với socket.id của kết nối mới. Chỉ cần đoán :-) –