我需要关闭连接才能确保消息被发送吗?因为无论是使用发送命令还是使用网络流,我的消息都没有被处理,直到我关闭连接。这是应该这样的方式还是我错过了什么?
好的,下面是代码。
private void connectButton_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient();
client.Connect(ip, port);
netStream = client.GetStream();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void disconnectButton_Click(object sender, EventArgs e)
{
if (client != null)
{
if (client.Connected)
{
client.Close();
client = null;
}
}
}
private void sendButton_Click(object sender, EventArgs e)
{
byte[] cmd = ToByteArray("bla bla bla");
netStream.Write(cmd, 0, cmd.Length);
netStream.Flush();
}
我不认为这与这种方法有关,但是请看一下。
public static byte[] ToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}