I'm trying to connect an HTML page to Socket.IO. Although I have experience in Object-Oriented languages, web is new and pretty frustrating for me so far. I've got a socket.io server running, which can be called to from C# and receives responses accordingly. However, now I need to connect it to an HTML page, which isn't working.
I've tried applying code from these three sites: 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
However, none of them even display the "user connected" message, even when literally copy-pasted.
The JS code I've written is this:
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);
And the HTML code:
<!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>
Without the io.attach(4567); my C# code doesn't find the websocket, however I get an io error if I try to use this port for HTML as well (EADDRINUSE: address already in use :::3000).
So, to summarize; why doesn't the HTML connect / send data to the socket?
socket.io clienton client side and you have to connect to server first. npm socket.io client