客戶端:
界面:
代碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; namespace Test2.Client { public partial class Form1 : Form { Socket clientSocket; IPEndPoint ipEndPoint; public Form1() { InitializeComponent(); button1.Text = "連接"; button2.Text = "發送"; button3.Text = "關閉"; } private void button1_Click(object sender, EventArgs e) { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ipEndPoint = new IPEndPoint(IPAddress.Parse("xxxxxxxxx"), 52555); clientSocket.Connect(ipEndPoint); } private void button2_Click(object sender, EventArgs e) { clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(textBox1.Text)); } private void button3_Click(object sender, EventArgs e) { SafeClose(clientSocket); } public void SafeClose( Socket socket) { if (socket == null) return; if (!socket.Connected) return; try { socket.Shutdown(SocketShutdown.Both); } catch { } try { socket.Close(); } catch { } } } }
服務器端:
界面:
代碼:
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace Test2.Server { public partial class Form1 : Form { public Form1() { InitializeComponent(); this.FormClosed += Form1_FormClosed; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { SafeClose(socketSend); } public void SafeClose( Socket socket) { if (socket == null) return; if (!socket.Connected) return; try { socket.Shutdown(SocketShutdown.Both); } catch { } try { socket.Close(); } catch { } } Socket socketSend; private void button1_Click(object sender, EventArgs e) { try { //點擊開始監聽時 在服務端創建一個負責監聽IP和端口號的Socket Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Any; //創建對象端口 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(52555)); socketWatch.Bind(point);//綁定端口號 MessageBox.Show("Watching"); socketWatch.Listen(10);//設置監聽 //創建監聽線程 Thread thread = new Thread(Listen); thread.IsBackground = true; thread.Start(socketWatch); } catch { } } void Listen(object o) { try { Socket socketWatch = o as Socket; while (true) { socketSend = socketWatch.Accept();//等待接收客戶端連接 //ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "連接成功!"); //開啟一個新線程,執行接收消息方法 Thread r_thread = new Thread(Received); r_thread.IsBackground = true; r_thread.Start(socketSend); } } catch { } } void Received(object o) { try { Socket socketSend = o as Socket; while (true) { //客戶端連接服務器成功后,服務器接收客戶端發送的消息 byte[] buffer = new byte[1024 * 1024 * 3]; //實際接收到的有效字節數 int len = socketSend.Receive(buffer); if (len == 0) { break; } string str = Encoding.UTF8.GetString(buffer, 0, len); this.Invoke(new Action(() => { listBox1.Items.Add(str + "\r\n"); })); } } catch { } } } }
ps:當客戶端使用connect方法連接服務器端時,服務端的accept方法接受請求,並且此時可以向客戶端發送消息:
代碼如下:
客戶端:
private void button1_Click(object sender, EventArgs e) { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ipEndPoint = new IPEndPoint(IPAddress.Parse("xxxxxx"), 52555); clientSocket.Connect(ipEndPoint); byte[] mybyte = new byte[1024 * 1024]; Task.Run(() => { int length= clientSocket.Receive(mybyte); string str = System.Text.Encoding.UTF8.GetString(mybyte, 0, length); this.textBox1.Invoke(new Action(()=> { this.textBox1.Text = str; })); }); }
服務器端:
void Listen(object o) { try { Socket socketWatch = o as Socket; while (true) { socketSend = socketWatch.Accept();//等待接收客戶端連接 Task.Run(() => { //string str = "123"; socketSend.Send(System.Text.Encoding.UTF8.GetBytes("123")); }); //ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "連接成功!"); //開啟一個新線程,執行接收消息方法 Thread r_thread = new Thread(Received); r_thread.IsBackground = true; r_thread.Start(socketSend); } } catch { } }