哈哈哈 public Form1()
{
InitializeComponent();
}
IPAddress ip;
IPEndPoint point = new IPEndPoint(IPAddress.Any,0);
string protocol;
Socket aimSocket;
Socket mySocket;
UdpClient RecUdpClient;
//IPEndPoint remote;
private void Form1_Load(object sender, EventArgs e)//初始化为UDP Server模式
{
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;//设定全局的IP
}
}
return AddressIP;
}
private void btnStart_Click(object sender, EventArgs e)//设置目标IP(Client),本地IP(Server)
{
try
{
if (protocol == "UDP Server")
{
aimSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
RecUdpClient = new UdpClient(new IPEndPoint(ip, Convert.ToInt32(txtPort.Text)));
MessageBox.Show("UDP Server创建成功");
Thread 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));
MessageBox.Show("UDP Client设置成功");
Thread 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);//绑定监听端口
MessageBox.Show("TCP Server绑定成功");
mySocket.Listen(10);//等待连接是一个阻塞过程,创建线程来监听
Thread 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);//连接服务器
MessageBox.Show("连接成功");
Thread thReceive = new Thread(TCReceive);
thReceive.IsBackground = true;
thReceive.Start();
}
}
catch
{}
}
评论