c# - 将数据从 C# 表单发送到节点服务器 socket.io
问题描述
我正在尝试从存储在名为ClientMsg
. 我SocketIoClientDotNet
用来与节点服务器通信。我的连接设置很好,但我无法将数据从表单发送到我的服务器。
有人可以告诉我该怎么做,因为我在网上找不到任何东西吗?
更新(添加代码):
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);
}
按钮:
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);
}
}
解决方案
您的代码的问题是您尝试在连接后直接发送消息,使用ClientMsg
最初为 null 的变量。
即使您在文本框中键入了一些内容,它也会保持为空,因为在您的按钮单击事件中,您声明了一个新ClientMsg
的本地的,因此您没有使用全局的。
应该是这样的:
// 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();
}
}