如何实现UDP通讯时的连续发送消息,目前我只实现发送一条消息就不能再发送,在网上搜找后说要使用多线程,但是我不会啊,请求高手指导》
Server:
private void btRec_Click(object sender, EventArgs e)
{
//在本機指定的端口接收
IPEndPoint remoteIpEndIPoint = new IPEndPoint(IPAddress.Any, 8002);
udpReceive = new UdpClient(remoteIpEndIPoint);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
//接收從遠程主機發送過來的消息
//while (true)
//{
//ref表示引用類型 IPPoint實例接收消息
byte[] receiveBytes = udpReceive.Receive(ref iep);
string returnData = Encoding.UTF8.GetString(receiveBytes);
txtSerRev.Text = returnData;
string strBack = "I am fine. Your IP address is " +iep.ToString();
byte[] data = Encoding.ASCII.GetBytes(strBack);
udpReceive.Send(data,data.Length,iep);
//}
}
CLient :
private void btSendMsg_Click(object sender, EventArgs e)
{
//初始化UdpClient
udpSend = new UdpClient();
//實際使用時應將192.168.80.128該為服務器的遠程IP
IPAddress remoteIPAddress = IPAddress.Parse(txtServerIP.Text);
IPEndPoint remoteIPEndPoint = new IPEndPoint(remoteIPAddress, 8002);
//將發送內容轉換為字節數組
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(txtSend.Text);
udpSend.Send(bytes, bytes.Length, remoteIPEndPoint);
bytes = udpSend.Receive(ref remoteIPEndPoint);
string str = Encoding.UTF8.GetString(bytes, 0, bytes.Length);
txtRec.Text = str;
}