Reputation: 2861
I want to build a connection from browser to server side which written in node.js
when the client side connect to the server , the server side will send a message to client and the server will receive message when the client click the send button.
but the client side can receive the message from server side , but server side can't receive message from client side
client side code
<center>
<input id="send" type="submit" value="send">
<p id="recv"></p>
</center>
<script src="library/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect("http://127.0.0.1:7000");
var send = document.getElementById("send");
var recv = document.getElementById("recv");
send.addEventListener("click",function () {
socket.emit("message","message_from_client");
});
socket.on("message",function (data) {
recv.innerHTML = data;
});
</script>
server side client
var socket = require("socket.io").listen(7000);
socket.on("connect",function () {
console.log("connect");
socket.emit("message","message_from_server");
});
socket.on("message",function (data) {
console.log(data);
});
Upvotes: 0
Views: 208
Reputation: 294
Can you try this code on server side? I seen it work.
var socket = require("socket.io").listen(7000);
socket.on("connect", function(client) {
console.log("connect");
client.emit("message", "message_from_server");
client.on("message", function(data) {
console.log(data);
});
});
You can check sample code and document on this link
Upvotes: 1
Reputation: 974
Try using io.sockets.emit('event', message)
on the client. This will send the message to all connected sockets, including the server.
Upvotes: 0