まず第一に、私の質問に誤りがあったことをお詫びしたいと思います。これは私の最初の仲間です!
次のコードを使用して、サーバーとクライアント間の接続をテストしようとしています。
仕組みは次のとおりです。特定のポートでソケットが開始され、クライアントがそのポートで接続を試みます。接続は部分的に成功し、「node server.js」が接続を開始し、ブラウザで「localhost」に移動すると、 :8000' html ページが生成されますが、ボタンをクリックしても何も起こりません。
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>
$(document).ready(function() {
var socket = io.connect("localhost:8000");
$("#join").click(function() {
var name = $("#name").val();
if (name != "") {
socket.emit("join", name);
}
});
socket.on("update", function(msg) {
$("#msgs").append("<li>" + msg + "</li>");
});
});
</script>
</head>
<body>
<input type="text" placeholder="Yor name" id="name">
<input type="button" name="join" id="join" value="Join!">
<ul id="msgs">
</ul>
</body>
server.js コード
var fs = require('fs'),
http = require('http'),
sio = require('socket.io');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-type': 'text/html'});
res.end(fs.readFileSync(__dirname + '/index.html'));
});
server.listen(8000, function() {
console.log('server is running');
});
var socket = sio.listen(server);
socket.on("connection", function (client) {
client.on("join", function(name) {
client.emit("update", name + "You have successfully sent your first message.");
});
});