【发布时间】:2019-10-16 21:05:22
【问题描述】:
我正在尝试将 HTML 页面连接到 Socket.IO。虽然我有面向对象语言的经验,但到目前为止,Web 还是新事物,让我感到非常沮丧。我有一个 socket.io 服务器正在运行,可以从 C# 调用它并相应地接收响应。但是,现在我需要将它连接到一个 HTML 页面,这不起作用。
我尝试过应用这三个网站的代码: Socket.io emit button press to all clients https://socket.io/get-started/chat https://www.tutorialspoint.com/socket.io/socket.io_quick_guide.htm
但是,它们甚至都没有显示“用户已连接”消息,即使是在字面上复制粘贴时也是如此。
我写的JS代码是这样的:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
var client;
//Whenever someone connects this gets executed
io.on('connection', function(socket) {
console.log('A user connected');
//Whenever someone disconnects this piece of code executed
socket.on('disconnect', function () {
console.log('A user disconnected');
});
socket.on('SERVER_CONNECTED', function () {
console.log('SERVER_CONNECTED');
client = socket.id;
io.sockets.connected[client].emit("SERVER_REGISTERED");
});
socket.on('MOVE_LEFT', function () {
console.log('MOVE_LEFT');
});
socket.on('MOVE_RIGHT', function () {
console.log('MOVE_RIGHT');
});
socket.on('SHOOT', function () {
console.log('SHOOT');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
io.attach(4567);
还有 HTML 代码:
<!doctype html>
<html lang="en">
<head>
<title>Socket IO Connection</title>
<script>
var socket = io();
function ClickLeft() {
socket.emit('MOVE_LEFT');
}
function ClickRight() {
socket.emit('MOVE_RIGHT');
}
function ClickShoot() {
socket.emit('SHOOT');
}
</script>
</head>
<body>
hello world
<button type="button" onclick="ClickLeft()">Links</button>
<button type="button" onclick="ClickRight()">Rechts</button>
<button type="button" onclick="ClickShoot()">PIEW PIEW</button>
</body>
</html>
如果没有 io.attach(4567);,我的 C# 代码找不到 websocket,但是如果我尝试将此端口也用于 HTML (EADDRINUSE: address already in use :::3000),则会收到 io 错误。
所以,总结一下;为什么 HTML 不连接/发送数据到套接字?
【问题讨论】:
-
您必须在客户端使用
socket.io client,并且您必须先连接到服务器。 npm socket.io client
标签: javascript html socket.io