Socket (socket) is a network programming interface independent of the protocol, which is mainly concentrated in the session layer and the transport layer in the OSI model. Socket actually represents a valid endpoint that communicates between two entities. The source IP address and source port, end point IP address, and end point port can be obtained via Socket. The user can connect multiple sockets into the same port so that there can be multiple connections for a single port. Creating a distributed program that can be used by many people via Socket Customer / Server, and all customers can work with unified front ends and communicate with the server. This is very similar to the calling process between old or new phones.
In .NET, System.Net.Sockets namespace provides a managed implementation of a Windows Sockets (Winsock) interface for developers who need to strictly control network access. The Socket class provides a wide range of methods and properties for network communications.
If the application only needs one thread during execution, use the following method, these methods apply to synchronous mode of operation.
If the currently used protocol (such as TCP), the server can listen to the connection using the Listen method. The Accept method handles any incoming connection request and returns a socket that can be used to communicate with the remote host. You can use this returned Socket to call the Send or Receive method. If you want to specify a local IP address and port number, call the BIND method before calling the Listen method. If Bind is not called, the underlying service provider will assign these values for you. Thereafter, you can use the LocalendPoint property to identify the IP address and port number assigned to the socket. If you want to connect to a listener host, call the Connect method. To perform data communication, call the Send or Receive method. If the currently useless connection protocol (such as UDP), you do not need to listen. Call the ReceiveFrom method Accept any incoming datagram. Use the Sendto method to send the datagram to the remote host. Develop a simple synchronous network chat program program into servers and clients. After the connection is successful, the server and client can be dialogue. The source code has detailed comments on each class / method / attribute that is more embarrassed to beginners involved. The following is the server-side code. using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets; using System.Threading; using System. Summary description of the text; namespace chat _ Socket {///
/// summary> private system.componentmodel.container Components = NULL; Public Form1 () {// // Windows Form Designer Support To Support // InitializationComponent (); // // Todo: Call in InitializationComponent Add any constructor code //} ///
/// summary> private void InitializeComponent () {this.rtbReceive = new System.Windows.Forms.RichTextBox (); this.rtbSend = new System.Windows.Forms.RichTextBox (); this.txtServer = new System. Windows.Forms.TextBox (); this.txtPort = new System.Windows.Forms.TextBox (); this.statusBar1 = new System.Windows.Forms.StatusBar (); this.btnListen = new System.Windows.Forms.Button (); This.btnsend = new system.windows.Forms.Button (); this.btnstop = new system.windows.forms.Button (); this.label1 = new system.windows.forms.label (); this. Label2 = new system.windows.forms.label (); this.label3 = new system.windows.forms.label (); this.label4 = new system.windows.forms.label (); this.suspendlayout (); / / // rtbreceive // this.rtbreceive.location = new system.drawing.point (80, 56); this.rtbreceive.name = "rtbreceive"; this.rtbreceive.size = new system.drawing.size (264, 96 ); This.rtbreceive.tabindex = 0; this.rtbreceive.text = ""; /// rtBsend // this .rtbsend.location = new system.drawing.point (80, 152); this.rtbsend.name = "RTBSEND"; this.rtbsend.size = new system.drawing.size (264, 96); this.rtbsend.tabindex = 1; this.rtbsend.text = ""; /// txtserver // this.txtserver.location = new system.drawing.point (72, 16); this.txtserver.name = "txtserver"; this.txtserver .Tabindex = 2; this.txtServer.Text = "127.0.0.1"; // // txtport // this.txtport.location = new system.drawing.point (288, 16); this.txtport.name = "TXTPORT "" This.txtport.size = new system.drawing.size (48, 21);
THISTXTPORT.TABINDEX = 3; this.txtport.text = "19811"; // // statusbar1 // this.statusbar1.Location = new system.drawing.point (0, 287); this.statusbar1.name = " Statusbar1 "; this.statusbar1.showpanels = true; this.statusbar1.size = new system.drawing.size (360, 22); this.statusbar1.tabindex = 4; this.statusbar1.text =" statusbar1 "; // / / btnlisten // this.btnlisten.location = new system.drawing.point (32, 256); this.btnlisten.name = "btnlisten"; this.btnlisten.tabindex = 5; this.btnlisten.text = "Start listening" "This.btnlisten.click = new system.eventhandler (this.btnlisten_click); // // btnsend // this.btnsend.location = new system.drawing.point (144, 256); this.btnsend.name =" BTNSEND "; this.btnsend.tabindex = 6; this.btnsend.text =" send information "; this.btnsend.click = new system.eventhandler (this.btnsend_click); // // btnstop // this.btnStop. Location = new system.drawing.point (256, 256); this.btnStop.name = "btnstop"; this.btnstop .Tabindex = 7; this.btnStop.text = "Stop listening"; this.btnstop.click = new system.EventHandler (this.btnstop_click; // // label1 // this.label1.Location = new system.drawing .Point (16, 16); this.label1.name = "label1"; this.label1.size = new system.drawing.size (56, 23); this.Label1.TabINDEX = 8; this.label1.text = Server: "; /// Label2 // this.label2.location = new system.drawing.point (216, 16); this.label2.name =" label2 "; this.label2.size = new system.drawing .Size (64, 23);
This.Label2.Tabindex = 9; this.label2.text = "Listening port:"; // // Label3 // this.label3.Location = new system.drawing.point (16, 64); this.label3.name = "label3"; this.label3.size = new system.drawing.size (64, 23); this.label3.Tabindex = 10; this.label3.text = "Receive information:"; /// Label4 // THIS.LABEL4.LOCATION = New System.drawing.Point (16, 152); this.label4.name = "label4"; this.label4.size = new system.drawing.size (64, 23); this.label4. TabINDEX = 11; this.label4.text = "Send information:"; /// Form1 // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size 360, 309); this.controls.add (this.label4); this.controls.add (this.label3); this.controls.add (this.label2); this.Controls.add (this.label1); this. .Controls.add (this.btnstop); this.Controls.add (this.btnsend); this.controls.add (this.btnlisten); this.Controls.add (this.statusbar1); this.controls.add (this .txtport); this.Controls.add (this.txtserver); This.Controls.add (this.rtbsend); this.controls.add (this.rtbreceive); this.name = "form1"; this.text = "chat program - server"; this.topmost = true; this.closing = new system.componentmodel.canceleventhandler (this.form1_closing); this.ResumeLayout (false);} #ENDREGION ///
/// summary> [STAThread] static void Main () {Application.Run (new Form1 ());} private void btnListen_Click (object sender, System.EventArgs e) {try {hostIPAddress = IPAddress.Parse (txtServer. TEXT); port = txtport.text;} catch {messagebox.show ("Please enter the correct IP address format");} Try {// By combined service host IP address and port number, IpendPoint class forms to the service connection point. Server = new IPEndPoint (hostIPAddress, Int32.Parse (port)); // Create a socket object to establish a connection with the server listeningSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); listeningSocket.Bind ( Server; // Bind the host port listeningsocket.Listen (50); // listens the port, waiting for the client connection request. 50 is the maximum number of waits accepted in the queue. STATUSBAR1.TEXT = " TXTSERVER.TEXT " port " txtserver.text " Start listening ..... "; // accept Listening to the connection of the socket request queue extracts the first pending connection request, then created and returned to the new socket. MySocket = listeningsocket.accept (); // A process can create one or more threads to perform some program code associated with the process. Use ThreadStart to delegate specifying program code executed by threads.
Thread thread = new Thread (new ThreadStart (ThreadProc)); thread.Start ();} catch (Exception ee) {statusBar1.Text = ee.Message;}} private void ThreadProc () {if (mySocket.Connected) {statusBar1 .Text = "Connect with customers."; While (true) {byte [] byterecv = new byte [256]; MySocket.Receive (byterecv, byterecv.length, 0); string strrecv = encoding.biGendianunicode.getstring (byterecv) ); rtbReceive.AppendText (strRecv "/ r / n");}}} private void btnStop_Click (object sender, System.EventArgs e) {try {listeningSocket.Close (); statusBar1.Text = "host" txtServer.Text "Port" txtport.text "Listening Stop";} catch {messagebox.show ("The listener has not started, shut down");}}}}} private void btnsend_click (object sender, system.eventargs e) {Try {string strsnd = " Server ---> " RTBSEND.TEXT " / r / n "; byte [] bytesend = encoding.bigenDianunicode.getbytes (strs); mysocket.send (bytesend, bytesend.length, 0);} catch {messagebox.show ("The connection has not yet been established, unable to send.");}} Private void form1_closing (Object Sender, System.componentmodel.canceleventArgs e) {Try {listeningsocket.close (); // Turn off the ScokeT connection before the window is closed and release all associated resources. } Catch {}}}}}} The following is a client source code for synchronous chat programs. Some may refer to the process server source code using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.Net; using System.Net.Sockets Using system.threading; use system.text; Namespace chat _ Socket_client {///
/// summary> public class Form1: System.Windows.Forms.Form {private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnStop; private System.Windows.Forms.Button btnSend; private System.Windows.Forms.TextBox txtPort; private System.Windows.Forms.TextBox txtServer; private System.Windows.Forms.RichTextBox rtbSend; private System.Windows.Forms.RichTextBox rtbReceive; private System.Windows.Forms.StatusBar statusBar1; private System.Windows.Forms.Button btnConnect; private IPAddress hostIPAddress; private IPEndPoint Server; private Socket sock ///
/// summary> private void initializecomponent () {this.label4 = new system.windows.forms.label (); this.label3 = new system.windows.forms.label (); this.label2 = new system. Windows.Forms.Label (); this.label1 = new system.windows.forms.Label (); this.btnstop = new system.windows.Forms.Button (); this.btnsend = new system.Windows.Forms.Button (); This.btnconnect = new system.windows.Forms.Button (); this.txtport = new system.windows.forms.textbox (); this.txtserver = new system.windows.Forms.TextBox (); this. rtbSend = new System.Windows.Forms.RichTextBox (); this.rtbReceive = new System.Windows.Forms.RichTextBox (); this.statusBar1 = new System.Windows.Forms.StatusBar (); this.SuspendLayout (); / / // label4 // this.label4.Location = new system.drawing.point (16, 152); this.label4.name = "label4"; this.label4.size = new system.drawing.size (64, 23 ); This.label4.tabindex = 22; this.label4.text = "Send information:"; // // label3 // this.label3.location = new System.drawing.Point (16, 64); this.label3.name = "label3"; this.label3.size = new system.drawing.size (64, 23); this.label3.tabindex = 21; this.label3 .Text = "Receive information:"; /// Label2 // this.label2.location = new system.drawing.point (216, 16); this.label2.name = "label2"; this.label2.size = New system.drawing.size (64, 23); this.label2.tabindex = 20; this.label2.text = "listening port:"; // // label1 // this.label1.location = new system.drawing. Point (16, 16); this.label1.name = "label1"; this.Label1.size =
New system.drawing.size (56, 23); this.label1.tabindex = 19; this.label1.text = "server:"; /// btnStop // this.btnstop.location = new system.drawing.point (256, 256); this.btnStop.name = "btnStop"; this.btnStop.tabindex = 18; this.btnStop.text = "Close connection"; this.btnstop.click = new system.eventhandler (this.btnstop_click ); // // btnsend // this.btnsend.location = new system.drawing.point (144, 256); this.btnsend.name = "btnsend"; this.btnsend.tabindex = 17; this.btnsend.text = "Send information"; this.btnsend.click = new system.eventhandler (this.btnsend_click); // // btnconnect // this.btnconnect.point = new system.drawing.point (32, 256); this. btnConnect.Name = "btnConnect"; this.btnConnect.TabIndex = 16; this.btnConnect.Text = "connection request"; this.btnConnect.Click = new System.EventHandler (this.btnConnect_Click); // // txtPort / / This.txtport.location = new system.drawing.point (288, 16); this.txtport.name = "txtport"; this.txtport.size = new system.drawing.size (48, 21); this.txtport.tabindex = 15; this.txtport.text = "19811"; // // txtserver // this.txtserver.location = new system.drawing.point (72, 16); this.txtServer.name = "txtserver"; this.txtServer.tabindex = 14; this.txtServer.Text = "127.0.0.1"; // // rtBsend // this.rtbsend.location = New System.drawing.point (80, 152); this.rtbsend.name = "rtbs"; this.rtbsend.size = new system.drawing.size (264, 96); this.rtbsend.tabindex = 13; this.rtbsend .Text =
""; // // rtbreceive // this.rtbreceive.location = new system.drawing.point (80, 56); this.rtbreceive.name = "rtbreceive"; this.rtbreceive.size = new system.drawing.size (264, 96); this.rtbreceive.tabindex = 12; this.rtbreceive.text = ""; /// statusbar1 // this.statusbar1.location = new system.drawing.point (0, 287); this. statusBar1.Name = "statusBar1"; this.statusBar1.ShowPanels = true; this.statusBar1.Size = new System.Drawing.Size (360, 22); this.statusBar1.TabIndex = 23; this.statusBar1.Text = "statusBar1 "; // // form1 // this.autoscalebasesize = new system.drawing.size (6, 14); this.clientsize = new system.drawing.size (360, 309); this.controls.add (this.statusbar1 This.controls.add (this.label4); this.controls.add (this.label3); this.Controls.add (this.label2); this.controls.add (this.label1); this.controls. Add (this.btnStop); this.controls.add (this.btnsend); this.controls.add (this.btnconnect); this.controls.add (this.txt Port); this.controls.add (this.txtserver); this.Controls.add (this.rtbsend); this.controls.add (this.rtbreceive); this.name = "form1"; this.text = "Chat Program - client "; this.closing = new system.componentmodel.canceleventhandler (this.form1_closing); this.ResumeLayout (false);} #ENDREGION ///