消息发送端TcpClient:
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect("127.0.0.1", sendport);
NetworkStream ns = tcpClient.GetStream();
if (ns.CanWrite)
{
//存储数据
Byte[] dataBytes = Encoding.UTF8.GetBytes(text_edit.Text);
//存储数据长度
Byte[] lengthBytes = BitConverter.GetBytes(dataBytes.Length);
//发送数据长度
ns.Write(lengthBytes, 0, lengthBytes.Length);
//发送数据
ns.Write(dataBytes, 0, dataBytes.Length);
//UpdataUIStatus(1, "发送退出命令成功\r\n");
//清空输入框
text_edit.Text = "";
}
else
{
//UpdataUIStatus(1, "发送退出命令失败\r\n");
return;
}
ns.Close();
}
catch (Exception eX)
{
UpdataUIStatus(1, eX.ToString() + "\r\n");
}
tcpClient.Close();
消息接收端TcpListener:
TcpListener listener = new TcpListener(IPAddress.Parse(hostName), portNum);
listener.Start(10);
isRun = true;
doStop = false;
while (!doStop)
{
//UpdateUIDelegate(1, "等待连接...\r\n");
TcpClient client = listener.AcceptTcpClient();
//UpdateUIDelegate(1, "已连接\r\n");
NetworkStream ns = client.GetStream();
try
{
//获取数据长度
byte[] lengthbuffer = new byte[sizeof(int)];
ns.Read(lengthbuffer, 0, lengthbuffer.Length);//读取网络流中的数据
//获取实际数据
byte[] databuffer = new byte[BitConverter.ToInt32(lengthbuffer, 0)];
ns.Read(databuffer, 0, databuffer.Length);//读取网络流中的数据
//显示接收的数据
UpdateUIDelegate(1, Encoding.UTF8.GetString(databuffer) + "\r\n");
ns.Close();
client.Close();
}
catch (Exception e)
{
UpdateUIDelegate(1, e.ToString() + "\r\n");
}
}
listener.Stop();
isRun = false;