Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.windows.forms;using system.net.sockets;using System.Net;using System.threading;namespace windowsformsapplication2{public partial class Form1:form {public Form1 () {InitializeComponent (); } Socket S; Thread MyThread; private static byte[] result = new byte[1024]; private void Button1_Click (object sender, EventArgs e) {string id = this.textBox1.Text; int post = Int. Parse (This.textBox2.Text); IPAddress Ips = ipaddress.parse (ID); Server IP Address s = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); Establish connection S.bind (new IPEndPoint (Ips,post)); Bind Port S.listen (10); Set maximum connection request MyThread = new Thread (listen); Mythread.start (S.remoteendpoint. ToString () + "Connection successful"); Mythread.isbackground = true; Mythread.start (); public void Show (String msg) {Textbox3.appendtext (msg + "\ r \ n"); } public void Listen () {while (true) { Socket Ceshi = s.accept (); Receives the connection and returns a new socket show (Ceshi. Remoteendpoint.tostring () + "Connection successful"); Ceshi. Send (Encoding.Default.GetBytes ("Lu Zhilin is two goods")); Thread Aax = new Thread (Jiaoliu); Aax. Start (Ceshi); }} public void Jiaoliu (object o) {socket AA = O as socket; while (true) {try {int receivenumber = AA. Receive (result); Reads the data textbox4.appendtext (AA) from the socket. Remoteendpoint.tostring () + Encoding.ASCII.GetString (result, 0, receivenumber) + "\ r \ n"); } catch (Exception ex) {AA. Shutdown (Socketshutdown.both); Aa. Close (); Break }}} private void Form1_Load (object sender, even Targs e) {control.checkforillegalcrossthreadcalls = false; } }}
•------------------related Classes--------------------------IPAddress class: Contains an IP address IPEndPoint class: Contains a pair of IP addresses and port numbers •-------------- ------Methods------------------------------socket (): Create a Socket bind (): Bind a local IP and port number (IPEndPoint) listen (): Let the socket listen for incoming connection attempts and specify the listening queue capacity connect (): Initializes a connection to another socket accept (): Receives the connection and returns a new socket send (): Output data to Socket receive (): Read data from Socket close (): Close socket (destroy connection)
C # Socket