using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; using Microsoft.VisualBasic.Devices; using System.Collections; namespace ke { public partial class Form1 : Form { static ArrayList myarray=new ArrayList(); static IPAddress[] ip = Dns.GetHostAddresses(Dns.GetHostName());///用DNS的方法求得本地IP地址数组 static IPAddress abc;///用来储存对方的IP地址 static string a;///用来储存发送的字符串 static string b = "";///用来储存接受的字符串 static int port = 9987;///端口号 static TcpListener tin;///建立一个TCP连接监听,我们将用他监听所有的连接请求 static Thread th1;///新建线程 static Thread th2;///新建线程 public string txer1, txer2, txer3, txer4;///记录内存使用状况 public Form1()///构造方法 { InitializeComponent();///初始化窗体 } public void fa(IPAddress a,int b,string c)///用来发送信息的公共方法,参数有3个 { try { IPEndPoint point = new IPEndPoint(a, b);///建立远程网络终结点 TcpClient tcp = new TcpClient();///建立一个TCP连接 tcp.Connect(point);///连接远程网络终结点 NetworkStream stm = tcp.GetStream();///用已经连接的TCP连接返回一个网络流 byte[] by = Encoding.Default.GetBytes(c);///将字符串转换为比特数组 stm.Write(by, 0, by.Length);///将字符数组写入网络流 stm.Dispose();///释放网络流的数据 stm.Close();///关闭网络流 tcp.Close();///关闭tcp连接 } catch { MessageBox.Show("请确保对方的电脑已经打开!(即是点击探明IP地址)"); } } public void zfa()///公共方法以方便之后的线程使用 { fa(abc, port, a);///引用fa公共方法 } public void ting()///公共方法用来接受数据 { foreach(IPAddress ips in ip) { if (ips.AddressFamily == AddressFamily.InterNetwork) { myarray.Add(ips); } } IPEndPoint point = new IPEndPoint(IPAddress.Parse(myarray[0].ToString()), port);///建立本地网络终结点 tin = new TcpListener(point);///用本地网络终结点建立一个TCP连接监听 tin.Start();///开始监听 while (true) { TcpClient tcp = tin.AcceptTcpClient();///用TCP连接监听返回一个TCP连接 NetworkStream stm = tcp.GetStream();///再用TCP连接返回一个网络流 byte[] by = new byte[9999];///新建一个比特数组