TcpClient的发送/关闭问题 [英] TcpClient send/close problem
本文介绍了TcpClient的发送/关闭问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是否需要关闭有消息联系实际发送的?因为无论我用send命令或使用网络数据流,我的邮件没有得到处理,直到我关闭连接。是,这是应该的方式是还是我失去了一些东西?
确定这里是代码。
私人无效connectButton_Click(对象发件人,EventArgs五)
{
试
{
客户端=新的TcpClient();
client.Connect(IP,端口);
的NetStream = client.GetStream();
}
赶上(异常前)
{
MessageBox.Show(ex.Message);
}
}
私人无效disconnectButton_Click(对象发件人,EventArgs五)
{
如果(客户端!= NULL)
{
如果(client.Connected)
{
client.Close();
客户端= NULL;
}
}
}
私人无效sendButton_Click(对象发件人,EventArgs五)
{
的byte [] CMD = ToByteArray(唧唧歪歪);
netStream.Write(CMD,0,cmd.Length);
netStream.Flush();
}
我不认为它与这个方法做,但看看
公共静态的byte [] ToByteArray(字符串str)
{
System.Text.ASCIIEncoding编码=新System.Text.ASCIIEncoding();
返回encoding.GetBytes(STR);
}
解决方案
您可能正在使用缓冲流,尝试调用.Flush方法,该方法被调用时clode也被自动调用。
Do I need to close the connection to have messages actually sent? Because whether I use send command or use a network stream, my messages don't get processed until I close connection. Is that the way it's supposed to be or am I missing something?
Ok here's the code.
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();
}
I don't think it has to do with this method but have a look.
public static byte[] ToByteArray(string str)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
return encoding.GetBytes(str);
}
解决方案
you are probably using buffered streams, try to call the .Flush method, which is also automatically called when clode is invoked.
这篇关于TcpClient的发送/关闭问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文