代码改变世界

C# UDP 网络聊天程序

2011-12-03 21:17  Andrew.Wangxu  阅读(1407)  评论(2编辑  收藏  举报

 学习了UDP协议的使用以及TCP协议的对比,各有各的优势!

个人理解优势区别如下:

1:UDP协议称为不可靠的传输协议,因为在从发送方接收方的传递过程中出现的数据丢失,协议本身并不能做出任何检测或者提示。

2:UDP速度比TCP快,因为UDP不需要先与对方建立连接,也不需要连接确认,因此速度要快的多。

理解下使用情景:

并不是说一个程序用UDP就用UDP 用TCP就用TCP,比如说QQ聊天,我们要开视频,语音,发送文件,文字。

其中开视频,语音就可以用UDP协议去做,文字也可以用UDP协议去做。而发送文件就用TCP去做啦,因为发送文件比较大的话 中途数据丢失,造成文件的完整性。。也会导致出问题。。而视频,在线电影这些就无所谓了,丢一点点也是看不出来的。

 

-------------------------------------------------分割线---------------------------------------

 

该程序测试了局域网,外网。

下面也说下连接局域网和外网的方式:

局域网:直接在软件上指向目标机的内网IP地址即可(如:192.168.1.223)

外网:指向目标机的外网IP地址,并且本机与目标机的路由器务必映射端口8889(可自行在源码里更改)

 

以下是截图与完整代码:

 

截图:

完整代码:

 

引入命名空间:

using System.Net;  
using System.Net.Sockets;
using System.Threading;

 

代码:

namespace UdpChatExample  
{
public partial class FormChat : Form
{
/// <summary>接收用</summary>
private UdpClient receiveUdpClient;
/// <summary>发送用</summary>
private UdpClient sendUdpClient;
/// <summary>和本机绑定的端口号</summary>
private const int port = 18001;
/// <summary>本机IP</summary>
IPAddress ip;
/// <summary>远程主机IP</summary>
IPAddress remoteIp;
public FormChat()
{
InitializeComponent();
//获取本机可用IP地址
IPAddress[] ips = Dns.GetHostAddresses(Dns.GetHostName());
ip = ips[ips.Length - 1];
//为了在同一台机器调试,此IP也作为默认远程IP
remoteIp = ip;
textBoxRemoteIP.Text = remoteIp.ToString();
textBoxSend.Text = "你好!";
}
private void FormChat_Load(object sender, EventArgs e)
{
//创建一个线程接收远程主机发来的信息
Thread myThread = new Thread(ReceiveData);
//将线程设为后台运行
myThread.IsBackground = true;
myThread.Start();
textBoxSend.Focus();
}
private void ReceiveData()
{
IPEndPoint local = new IPEndPoint(ip, port);
receiveUdpClient = new UdpClient(local);
IPEndPoint remote = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
try
{
//关闭udpClient时此句会产生异常
byte[] receiveBytes = receiveUdpClient.Receive(ref remote);
string receiveMessage = Encoding.Unicode.GetString(
receiveBytes, 0, receiveBytes.Length);
AddItem(listBoxReceive, string.Format("来自{0}:{1}", remote, receiveMessage));
}
catch
{
break;
}
}
}
private void buttonSend_Click(object sender, EventArgs e)
{
Thread t = new Thread(SendMessage);
t.IsBackground = true;
t.Start(textBoxSend.Text);
}
/// <summary>发送数据到远程主机</summary>
private void SendMessage(object obj)
{
string message = (string)obj;
sendUdpClient = new UdpClient(0);
byte[] bytes = System.Text.Encoding.Unicode.GetBytes(message);
IPEndPoint iep = new IPEndPoint(remoteIp, port);
try
{
sendUdpClient.Send(bytes, bytes.Length, iep);
AddItem(listBoxStatus, string.Format("向{0}发送:{1}", iep, message));
ClearTextBox();
}
catch (Exception ex)
{
AddItem(listBoxStatus, "发送出错:" + ex.Message);
}
}
delegate void AddListBoxItemDelegate(ListBox listbox, string text);
private void AddItem(ListBox listbox, string text)
{
if (listbox.InvokeRequired)
{
AddListBoxItemDelegate d = AddItem;
listbox.Invoke(d, new object[] { listbox, text });
}
else
{
listbox.Items.Add(text);
listbox.SelectedIndex = listbox.Items.Count - 1;
listbox.ClearSelected();
}
}
delegate void ClearTextBoxDelegate();
private void ClearTextBox()
{
if (textBoxSend.InvokeRequired)
{
ClearTextBoxDelegate d = ClearTextBox;
textBoxSend.Invoke(d);
}
else
{
textBoxSend.Clear();
textBoxSend.Focus();
}
}
}
}

如果编译有问题的朋友,可以到下面地址下载我上传的资源文件,谢谢。

下载地址:https://files.cnblogs.com/andrew-blog/UdpChatExample.rar

参考:http://www.wxzzz.com/?id=46