1、界面设计

2、编程
namespace NetWork
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
IPAddress ip;
IPEndPoint point = new IPEndPoint(IPAddress.Any,0);
string protocol;
Socket aimSocket;
Socket mySocket;
UdpClient RecUdpClient;
Thread thReceive = null;
Boolean threadFlag = false;
//初始化
private void Form1_Load(object sender, EventArgs e)
{
cobProtocol.SelectedIndex = 0;
txtIP.Text = GetAddressIP();
Control.CheckForIllegalCrossThreadCalls = false;
}
string GetAddressIP()
{
string AddressIP = “”;
foreach (IPAddress _IPAddress in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
if (_IPAddress.AddressFamily.ToString() == “InterNetwork”)
{
AddressIP = _IPAddress.ToString();
ip = _IPAddress;
}
}
return AddressIP;
}
//打开按键处理函数
private void btnStart_Click(object sender, EventArgs e)
{
if (btnStart.Text == “打开”)
{
btnStart.Enabled = false;
threadFlag = true;
ConnectNet();
btnStart.Text = “关闭”;
btnStart.Enabled = true;
}
else
{
btnStart.Enabled = false;
threadFlag = false;
CloseNet();
btnStart.Text = “打开”;
btnStart.Enabled = true;
}
}
//协议选择处理函数
private void cobProtocol_SelectedIndexChanged(object sender, EventArgs e)
{
protocol = cobProtocol.SelectedItem.ToString();
if (protocol == "UPD Server" || protocol == "TCP Server")
{
lblIP.Text = "本地IP地址:";
lblPort.Text = "本地端口号:";
}
else if (protocol == "UDP Client" || protocol == "TCP Client")
{
lblIP.Text = "远程IP地址:";
lblPort.Text = "远程端口号:";
}
}
//发送按键处理函数
private void btnSend_Click(object sender, EventArgs e)
{
try
{
byte[] buffer = Encoding.Default.GetBytes(txtSend.Text);
aimSocket.SendTo(buffer, point);
}
catch
{ }
}
//连接网络
private void ConnectNet()
{
try
{
if (protocol == "UDP Server")
{
aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
RecUdpClient = new UdpClient(new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)));
lbStatus.Text = "连接成功";
thReceive = new Thread(USReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
else if (protocol == "UDP Client")//UPD客户端,目标IP和端口 调用Socket.SendTo
{
aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//建立通信的Socket
ip = IPAddress.Parse(txtIP.Text);
point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
lbStatus.Text = "连接成功";
thReceive = new Thread(UCReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
else if (protocol == "TCP Server")
{
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//绑定端口号
mySocket.Bind(point);//绑定监听端口
lbStatus.Text = "连接成功";
mySocket.Listen(10);//等待连接是一个阻塞过程,创建线程来监听
thReceive = new Thread(TSReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
else if (protocol == "TCP Client")
{
ip = IPAddress.Parse(txtIP.Text);//目标IP
point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));//目标端口
aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
aimSocket.Connect(point);//连接服务器
lbStatus.Text = "连接成功";
thReceive = new Thread(TCReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
}
catch(Exception exp)
{
if(protocol == "UPD Server" || protocol == "TCP Server")
{
mySocket.Close();
}
else if (protocol == "UDP Client" || protocol == "TCP Client")
{
aimSocket.Close();
}
lbStatus.Text = "连接失败";
Console.WriteLine(exp.Message);
}
}
//关闭网络
private void CloseNet()
{
Thread.Sleep(1000);
if (protocol == "UPD Server" || protocol == "TCP Server")
{
mySocket.Close();
//mySocket.Dispose();
}
else if (protocol == "UDP Client" || protocol == "TCP Client")
{
aimSocket.Close();
}
lbStatus.Text = "连接关闭";
}
//TCP Server接收线程
void TSReceive()
{
aimSocket = mySocket.Accept();//服务端监听到的Socket为服务端发送数据的目标socket
byte[] buffer = new byte[1024];
while (threadFlag)
{
try
{
int r = aimSocket.Receive(buffer);//接收到监听的Socket的数据
if (r == 0)
{
break;
}
string strRec = Encoding.Default.GetString(buffer, 0, r);
txtRec.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec + "\r\n");
}
catch
{ }
}
}
//TCP Client接收线程
void TCReceive()
{
byte[] buffer = new byte[1024];
while (threadFlag)
{
try
{
int r = aimSocket.Receive(buffer);
if (r == 0)
{
break;
}
string strRec = Encoding.Default.GetString(buffer, 0, r);
txtRec.AppendText(aimSocket.RemoteEndPoint.ToString() + ":" + strRec + "\r\n");
}
catch
{ }
}
}
//UDP Clinet接收线程
void UCReceive()
{
byte[] buffer = new byte[1024];
while (true)
{
try
{
IPEndPoint ss = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)(ss);
int r = aimSocket.ReceiveFrom(buffer, ref Remote);//接收目标IP Remote 发送过来的数
string strRec = Encoding.Default.GetString(buffer,0,r);
txtRec.AppendText(Remote.ToString() + ": " + strRec + "\r\n");
}
catch
{ }
}
}
//UDP Server接收线程
void USReceive()
{
while (true)
{
try
{
byte[] buffer = RecUdpClient.Receive(ref point);
string strRec = Encoding.Default.GetString(buffer);
txtRec.AppendText(point.ToString() + ": " + strRec + "\r\n");
}
catch
{ }
}
}
//接收区域清除
private void btRecClear_Click(object sender, EventArgs e)
{
txtRec.Clear();
}
//发送区域清除
private void btSendClear_Click(object sender, EventArgs e)
{
txtSend.Clear();
}
}
}
3、问题及解决
以前在关闭网络中有线程Abort()函数,在频繁打开/关闭网络时经常出现异常,测试证明该方法结束线程并不可靠。
解决办法:不终止线程,让线程自动退出。在线程函数中将while(true)换成While(flag),控制flag间接使线程退出。