C# socket 客户端
//这里创建的是负责通信的socket,这个socket 不分 服务器或客户端 public static Socket socketCommunication = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public Form1() { InitializeComponent(); } //打开链接 服务器 private void button2_Click(object sender, EventArgs e) { IPAddress ip = IPAddress.Parse(txtServer.Text); IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text)); try { socketCommunication.Connect(point); DateTime dt = DateTime.Now; dt.ToUniversalTime().ToString(); this.listBox1.Items.Add(dt.ToUniversalTime().ToString() + "链接成功"); } catch (Exception e1) { Console.WriteLine("Thread aborted."); socketCommunication.Connect(point); DateTime dt = DateTime.Now; dt.ToUniversalTime().ToString(); this.listBox1.Items.Add(dt.ToUniversalTime().ToString() + "链接失败"); } } //发送数据 private void button1_Click(object sender, EventArgs e) { //接受 string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = socketCommunication.Receive(recvBytes, recvBytes.Length, 0); recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes); //发送 string str = "vsvvsvd"; //把要发送的消息转为字节数组 byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); socketCommunication.Send(buffer); // socketCommunication.Close(); }