Reputation: 3
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?
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);
}
}
Upvotes: 0
Views: 2477
Reputation: 4733
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();
}
}
Upvotes: 2