Reputation: 659
I am new to socket.io and trying to replicate the example given at http://socket.io/get-started/chat/
<!doctype html>
<html>
<head>
<title>Socket.IO chat</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font: 13px Helvetica, Arial; }
form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
#messages { list-style-type: none; margin: 0; padding: 0; }
#messages li { padding: 5px 10px; }
#messages li:nth-child(odd) { background: #eee; }
</style>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery.js"></script>
<script>
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
</head>
<body>
<ul id="messages"></ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
</html>
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('index.html');
});
io.on('connection', function(socket){
console.log('message pinged--------------');
socket.on('chat message', function(msg){
console.log('chat message ' + msg);
});
socket.on('message', function(obj){
console.log("meg from server");
});
});
http.listen(8079, function(){
console.log('listening on *:8079');
});
console.log('Server is running...dnt worry!!');
{
"name": "socket-chat-example",
"version": "0.0.1",
"description": "my first socket.io app",
"dependencies": {
"express": "4.3.1",
"socket.io": "1.0.2"
}
}
Message is not giving pinged.. socket.on('chat message', function(msg){ console.log('chat message ' + msg); });
while i am able to know when the message is pinged but not what is pinged
Upvotes: 0
Views: 526
Reputation: 23337
It doesn't work as expected because you add submit
handler to non-existing form. The form is being created after your script is executed.
To fix this you should either wrap your js code in document-ready function:
$(function() {
var socket = io();
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
or put your js code to the very end of the body
tag.
Upvotes: 1