C# socket 客戶端
阿新 • • 發佈:2021-08-28
//這裡建立的是負責通訊的socket,這個socket 不分 伺服器或客戶端 public static Socket socketCommunication = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); public Form1() { InitializeComponent(); } //開啟連結 伺服器 private void button2_Click(objectsender, 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(); }