It turns out that I have a server in nodejs with http and some express:
const http = require('http');
const express = require('express');
const app = express();
const io = require('socket.io');
const server = http.createServer(app);
app.set('port', process.env.PORT || 3000);
app.use(express.static(__dirname + "/public"));
server.listen(app.get('port'), function(){
console.log("Servidor iniciadio");
})
var socket = io.listen(server);
socket.on('connection', function(socket) {
console.log("Nuevo cliente conectado");
})
socket.on('mensaje-cliente', function(data) {
console.log(data);
})
And I also have a client:
$(function() {
//socket iniciado
var socket = io();
//variables
var message = $("#chat-message");
var chat = $("#chat");
message.focus();
$("#message-box").submit(function (e) {
e.preventDefault();
socket.emit('mensaje-cliente', message.val());
})
});
for which I work with jquery and socket.io.
My problem is that the socket connection doesn't work for me, it doesn't show me the messages from the client in the console as I tell the server, it doesn't give me an error in the console either, it just doesn't happen. What am I doing wrong?
This is my html in case you need to check it too:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Chat</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<style media="screen">
#chat {
height: 400px;
border: 1px solid #000;
width: 20%;
}
#message-box {
width: 20%;
}
</style>
</head>
<body>
<!--Muesta los textos del chat -->
<div class="container">
<div id="chat">
</div>
<!-- Controloes del chat -->
<form id="message-box">
<input type="text" id="chat-message">
<input type="submit" value="Enviar">
</form>
</div>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="/socket.io/socket.io.js"></script>
<script src="main.js"></script>
</body>
</html>
There you can see that I have both jquery and socket io running.
I already found the solution and the problem is that the on('connection') of the server has nothing to do with that of the socket. That's why the confusion, so it would be more or less like this: