0
votes

So I'm playing around with socket.io trying to make a multiplayer mini-game, but the socket.emit() function I'm using client-side isn't working. It throws no error neither on client browser nor on server console. It just won't emit the event. Maybe it's the socket.on() server-side that doesn't receive it.

There's an html folder that contains jquery.js, socket.io-1.2.0.js, index.html, main.js and style.css

Here is the essential code but there's a pastebin with the whole code at the end:

Client-side:

const socket = io();
socket.emit('pos', player);

socket.on('pos', (pos) => {
  if (player.show = true) {
    canvasCtx.fillStyle = "#7c5c5c";
    canvasCtx.fillRect(player.x, player.y, playerwidth, playerheight);

    canvasCtx.fillStyle = "grey";
    canvasCtx.fillRect(player.x, player.y + playerheight, shadow_width, 
    shadow_height);
  }

I have a perfectly working canvas and player dictionnary.

Server-side:

var path = require("path");
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static('html'))
app.get('/', function(req, res){
  res.sendFile(path.resolve(__dirname + '/html/index.html'));
});

io.on('connection', function(socket){
  socket.on('pos', (player) => {
    io.emit('pos', player);
    console.log('Received player data with values : ' + player.x + ' for x ' 
    + player.y + ' for y '+ player.skin + 'as a skin')
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

I used npm to install express and socket.io

The pastebin : https://pastebin.com/wrzr9C76

Thank you

1

1 Answers

0
votes

You shouldn't need to provide your own copy of the socket.io client library. When socket.io is initialized it adds middleware to serve socket.io.js on the path /socket.io/socket.io.js. You can verify this by visiting http://localhost:3000/socket.io/socket.io.js when you run your app.

So in your html, instead of <script src="socket.io-1.2.0.js"></script>, try using <script src="/socket.io/socket.io.js"></script>. This should ensure that your issue isn't caused by a mismatch between client and server versions of socket.io.