简体   繁体   中英

client can't send data to server side?

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);

});

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

Try using io.sockets.emit('event', message) on the client. This will send the message to all connected sockets, including the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM