我看书上的测试IP都是本地主机,所以没多少问题,但如何真正运用到网络上,可能还要有很多注意的细节。。。
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Threading.Tasks; 9 using System.Windows.Forms; 10 using System.Net; 11 using System.Net.Sockets; 12 13 namespace WindowsFormsApplication1 14 { 15 public partial class Form1 : Form 16 { 17 public Form1() 18 { 19 InitializeComponent(); 20 } 21 22 private void button1_Click(object sender, EventArgs e) 23 { 24 TcpListener tcplistener = null; 25 IPAddress ipaddress = IPAddress.Parse(textBox1.Text); 26 int port = Convert.ToInt32(textBox2.Text); 27 tcplistener = new TcpListener(ipaddress, port); 28 tcplistener.Start(); 29 richTextBox1.Text = "等待连接。。。\n"; 30 TcpClient tcpclient = null; 31 if (tcplistener.Pending()) 32 tcpclient = tcplistener.AcceptTcpClient(); 33 else 34 tcpclient = new TcpClient(textBox1.Text, port); 35 richTextBox1.Text += "连接成功!!\n"; 36 tcpclient.Close(); 37 tcplistener.Stop(); 38 } 39 40 private void button2_Click(object sender, EventArgs e) 41 { 42 richTextBox2.Text = string.Empty; 43 UdpClient udpclient = new UdpClient(Convert.ToInt32(textBox4.Text)); 44 udpclient.Connect(textBox3.Text, Convert.ToInt32(textBox4.Text)); 45 Byte[] sendBytes = Encoding.Default.GetBytes(textBox5.Text); 46 udpclient.Send(sendBytes, sendBytes.Length); 47 IPEndPoint ipendpoint = new IPEndPoint(IPAddress.Any, 0); 48 Byte[] receiveBytes = udpclient.Receive(ref ipendpoint); 49 string returnData = Encoding.Default.GetString(receiveBytes); 50 richTextBox2.Text = "接收到的信息: " + returnData.ToString(); 51 richTextBox2.Text += "\n 这条信息来自主机 " + ipendpoint.Address.ToString() 52 + " 上的 " + ipendpoint.Port.ToString() +"端口"; 53 } 54 } 55 }