demathieu demathieu - 4 months ago 58
Javascript Question

socket IO send form data from client to server

I'm trying to send a simple message from a form to my server using socket.io. Sadly enough this is failing, I know the client has a connection with the server, but it does not appear to receive the messages.

Could someone explain to me why my code is failing?

Server.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');
});

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

io.on('connection', function(socket){
console.log('connection is er');
socket.on('message', function(msg){
console.log('test');
console.log('message: ' + msg);
});
});


index.html :

<html>
<body>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('#form').submit(function(){
socket.emit('message', $('#Input').val());
//socket.emit('message', "Input");
//$('#Input').val('');
return false;
});
</script>
<form id = "form" action = "">
Input: <input type="text" id="Input"><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

Answer

It looks like your client is using socket.io JS file from socket.io website but you didn't specified host and port of YOUR server.

Check out the documentation http://socket.io/docs/#using-with-the-express-framework you need to do something like

var socket = io.connect('http://localhost:8001');