110,538
社区成员
发帖
与我相关
我的任务
分享
发送消息的代码是:
IPEndPoint m_endPoint = new IPEndPoint(IPAddress.Parse(toIP), 8082);
UdpClient client = new UdpClient();
byte[] sendByte = System.Text.Encoding.UTF8.GetBytes(sendMsg.ToCharArray());
while (true)
{//若发送三次都失败,则提示消息发送失败。
try
{
client.Send(sendByte, sendByte.Length, m_endPoint);
break;
}
catch
{
if (retry < 3)
{
retry++;
continue;
}
else
{
break;
}
}
}
client.Close();
}
接收的代码:
bool UdpStatus = true;
byte[] myByte = null;
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8082);
UdpClient server = new UdpClient(endPoint);
while (UdpStatus)
{
try
{
myByte = server.Receive(ref endPoint);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
//消息处理
。。。。。。
}
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
int retry = 0;
FileStream myFile = new FileStream(ofd.FileName, FileMode.Open);
MessageBox.Show(ofd.FileName);
byte[] bty = new byte[4096];
IPEndPoint m_endPoint = new IPEndPoint(IPAddress.Parse(toIP), 8082);
UdpClient mclient = new UdpClient();
while(myFile.Read(bty, 0, 4096)>0)
//myFile.Flush();
//myFile.Close();
//while (true)
{//若发送三次都失败,则提示消息发送失败。
try
{
mclient.Send(bty, bty.Length, m_endPoint);
break;
}
catch(Exception f)
{
MessageBox.Show(f.Message);
if (retry < 3)
{
// retry++;
//continue;
}
else
{
MessageBox.Show("文件传送失败!");
break;
}
}
}
mclient.Close();
}
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
int retry = 0;
FileStream myFile = new FileStream(ofd.FileName, FileMode.Open);
MessageBox.Show(ofd.FileName);
byte[] bty = new byte[myFile.Length+2000];
myFile.Read(bty, 0, Convert.ToInt32(myFile.Length));
myFile.Flush();
myFile.Close();
IPEndPoint m_endPoint = new IPEndPoint(IPAddress.Parse(toIP), 8082);
UdpClient mclient = new UdpClient();
while (true)
{//若发送三次都失败,则提示消息发送失败。
try
{
mclient.Send(bty, bty.Length, m_endPoint);
break;
}
catch(Exception f)
{
MessageBox.Show(f.Message);
if (retry < 3)
{
retry++;
continue;
}
else
{
MessageBox.Show("文件传送失败!");
break;
}
}
}
mclient.Close();
}
byte[] bty = new byte[4096];
while (myFile.Read(bty, 0, 4096) > 0)
{
mclient.Send(bty, bty.Length, m_endPoint);
}