基本的な送受信をしようとして、VPS で node.js/socket.io をいじっています。大丈夫ですべてを承認しているようで、VPSでこれを取得します。websocket writing 5:::{"name":"news","args":[{"hello":"world"}]}
ただし、クライアントが切断されたときにのみクライアントに何も表示されません。それらが切断された後、「世界」という言葉が表示されます。それらがまだ接続されている間にその単語を見るべきではないので、私は何か間違ったことをしていますか? 助けてくれてありがとう。
私はこのコードを使用しています:
クライアント:
<!doctype html>
<html>
<head>
<title>web sockets</title>
<meta charset="utf-8">
<script src="http://IP-ADDRESS/socket.io/socket.io.js"></script>
<script>
var socket = io
.connect('http://IP-ADDRESS:80');
socket.on('news', function (data) {
console.log(data);
writeMessage(data);
socket.emit('my other event', { my: 'data' });
});
function writeMessage(msg) {
var msgArea = document.getElementById("msgArea");
if (typeof msg == "object") {
msgArea.innerHTML = msg.hello;
}
else {
msgArea.innerHTML = msg;
}
}
</script>
</head>
<body>
<div id="msgArea">
</div>
</body>
</html>
サーバ:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
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) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});