send data from C# form to node server socket.io

强颜欢笑 提交于 2019-12-25 02:26:56

问题


I am trying to send data from a C# form which I have stored in a variable called ClientMsg. I am using SocketIoClientDotNet to communicate to the node server. I have the connection setup which is all fine but I am unable to send data from the form to my server.

Could someone tell me how to do this as I cant find anything online?

Code Code Node

Update (added code):

private void socketManager()
    {
        var server = IO.Socket("http://localhost");
        server.On(Socket.EVENT_CONNECT, () =>
        {
            UpdateStatus("Connected");
        });
        server.On(Socket.EVENT_DISCONNECT, () =>
        {
            UpdateStatus("disconnected");
        });
        server.Emit("admin", ClientMsg);
    }

Button:

private void btnSend_Click(object sender, EventArgs e)
    {
        String ClientMsg = txtSend.Text;
        if (ClientMsg.Length == 0)
        {
            txtSend.Clear();
        }
        else
        {
            txtSend.Clear();
            lstMsgs.Items.Add("You:" + " " + ClientMsg);
        }
    }

回答1:


The problem with your code is that you're trying to send a message directly after connecting, using the ClientMsg variable which is null at first.
Even if you type something in your textbox, it'll stay null because in your button click event you're declaring a new ClientMsg which is local, so you're not working with the global one.

Here's how it should be:

// Save your connection globally so that you can
// access it in your button clicks etc...
Socket client;

public Form1()
{
    InitializeComponent();
    InitializeClient();
}

private void InitializeClient()
{
    client = IO.Socket("http://localhost");
    client.On(Socket.EVENT_CONNECT, () =>
    {
        UpdateStatus("Connected");
    });
    client.On(Socket.EVENT_DISCONNECT, () =>
    {
        UpdateStatus("disconnected");
    });
}

private void btnSend_Click(object sender, EventArgs e)
{
    String clientMsg = txtSend.Text;
    if (ClientMsg.Length == 0)
    {
        // No need to clear, its already empty
        return;
    }
    else
    {
        // Send the message here
        client.Emit("admin", clientMsg);
        lstMsgs.Items.Add("You:" + " " + clientMsg);
        txtSend.Clear();
    }
}


来源:https://stackoverflow.com/questions/51909373/send-data-from-c-sharp-form-to-node-server-socket-io

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!