C#基于TCP协议的通信无法接收服务器发送的数据
C#基于TCP协议的通信无法接收服务器发送的数据,请帮忙解决,代码如下:private void btnOpen_Click(object sender, EventArgs e)
{
if (!(Client == null) && Client.Connected)
{
MessageBox.Show("连接已建立");
return;
}
try
{
strIP = txtIP.Text.Trim();
//将IP地址字符串转化为IPAddress实例
ip = IPAddress.Parse(strIP);
int port = Int32.Parse(txtPort.Text.Trim());
Client = new TcpClient();
ServerEP = new IPEndPoint(ip, port);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(ServerEP);
if (Client.Connected)
{
MessageBox.Show("连接成功");
if (!txtRcv.InvokeRequired)
{
Thread thread = new Thread(new ThreadStart(Receive));
thread.Start();
}
else
{
txtRcv.Invoke(new SynReceive(Receive));
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
/// <summary>
/// 声明获取事件的委托
/// </summary>
private delegate void SynReceive();
/// <summary>
/// 线程接收函数
/// </summary>
public void Receive()
{
int buffersize=1024;
byte[] rcvBuffer=new byte[buffersize];
NetworkStream Stream=Client.GetStream();
while(true)
{
String strRcv=ServerEP.ToString()+"\r\n";
int recBytes=Stream.Read(rcvBuffer,0,rcvBuffer.Length);
strRcv=Encoding.ASCII.GetString(rcvBuffer);
//txtRcv.AppendText(strRcv);
}
}