Instance parsing socket programming model-Server

Source: Internet
Author: User
Socket (socket) is a protocol-independent network programming interface. In the OSI model, it focuses on the Session Layer and transmission layer. Socket actually represents a valid endpoint for communication between two entities. You can obtain the source IP address, source port, destination IP address, and destination port through socket. You can connect multiple sockets to the same port so that multiple connections can be established on a single port. Through Socket Client/Server programming, you can create a distributed architecture that can be used by many people. Program And all customers can work with a unified front-end and communicate with the server. This is very similar to the call process between old-fashioned or new-style telephones.

In. net, the system. net. Sockets namespace provides a managed implementation of the Windows Sockets (Winsock) interface for developers who need to strictly control network access. The socket class provides a rich set of methods and attributes for network communication.

If the application only needs one thread during execution, use the following methods, which are applicable to synchronous operation mode.

If you are using a connection-oriented protocol (such as TCP), the server can use the listen method to listen for connections. The accept method processes any incoming connection requests and returns the socket that can be used to communicate with the remote host. You can use the returned socket to call the send or receive method. To specify the local IP address and port number, call the bind method before calling the listen method. If BIND is not called, the basic service provider assigns these values to you. Then, you can use the localendpoint attribute to identify the IP address and port number allocated to the socket. To connect to the listener host, call the connect method. To perform data communication, call the send or receive method.

If you are using a non-connection protocol (such as UDP), you do not need to listen for connections. Call the receivefrom method to accept any incoming datagram. The sendto method can be used to send a datagram to a remote host.

Develop a simple synchronous network chat program, which can be divided into servers and clients. After the connection is successful, the server and the client can communicate with each other. The source code provides detailed comments on every class, method, and attribute that is difficult for beginners to understand. Below are the server sideCode.

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. text;

Namespace chat_socket

{

/// <Summary>

/// Summary of form1.

/// </Summary>

Public class form1: system. Windows. Forms. Form

{

Private system. Windows. Forms. statusbar statusbar1;

Private system. Windows. Forms. Label label1;

Private system. Windows. Forms. Label label2;

Private system. Windows. Forms. Label label3;

Private system. Windows. Forms. Label label4;

Private system. Windows. Forms. RichTextBox rtbreceive;

Private system. Windows. Forms. RichTextBox rtbsend;

Private system. Windows. Forms. textbox txtserver;

Private system. Windows. Forms. textbox txtport;

Private system. Windows. Forms. Button btnlisten;

Private system. Windows. Forms. Button btnsend;

Private system. Windows. Forms. Button btnstop;

Private IPaddress hostipaddress = IPaddress. parse ("127.0.0.1 ");

Private ipendpoint server;

Private socket listeningsocket;

Private socket mysocket;

String port;

/// <Summary>

/// Required designer variables.

/// </Summary>

Private system. componentmodel. Container components = NULL;

Public form1 ()

{

//

// Required for Windows Form Designer support

//

Initializecomponent ();

//

// Todo: add Any constructor code after initializecomponent calls

//

}

/// <Summary>

/// Clear all resources in use.

/// </Summary>

Protected override void dispose (bool disposing)

{

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

# Region code generated by Windows Form Designer

/// <Summary>

/// The designer supports the required methods-do not use the code editor to modify

/// Content of this method.

/// </Summary>

Private void initializecomponent ()

{

This. rtbreceive = new system. Windows. Forms. RichTextBox ();

This. rtbsend = new system. Windows. Forms. RichTextBox ();

This.txt Server = new system. Windows. Forms. Textbox ();

This.txt Port = 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.txt server. Location = new system. Drawing. Point (72, 16 );

This.txt server. Name = "txtserver ";

This.txt server. tabindex = 2;

This.txt server. Text = "127.0.0.1 ";

//

// Txtport

//

This.txt port. Location = new system. Drawing. Point (288, 16 );

This.txt port. Name = "txtport ";

This.txt port. size = new system. Drawing. Size (48, 21 );

This.txt port. tabindex = 3;

This.txt port. 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 message ";

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 = "sending message :";

//

// 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.txt port );

This.controls.add(this.txt server );

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>

/// Main entry point of the application.

/// </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 ("enter the correct IP address format ");}

Try

{// The connection point to the service is formed through the Host IP address and port number of the combined service, ipendpoint class.

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); // listening port, waiting for client connection request. 50 is the maximum number of incoming connections that can be accommodated in the queue.

Statusbar1.text = "host" + txtserver. Text + "Port" + txtport. Text + "Start listening .....";

// Accept extracts the first pending connection request from the connection request queue of the listening socket synchronously, and then creates and returns the new socket.

Mysocket = listeningsocket. Accept ();

// A process can create one or more threads to execute some program code associated with the process. Use threadstart to delegate the program code to be executed by the thread.

Thread thread = new thread (New threadstart (threadproc ));

Thread. Start ();

}

Catch (exception ee) {statusbar1.text = ee. Message ;}

}

Private void threadproc ()

{

If (mysocket. Connected)

{

Statusbar1.text = "establish a connection with the customer .";

While (true)

{

Byte [] byterecv = new byte [1, 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 + "listener stopped ";

}

Catch {MessageBox. Show ("the listener has not started yet, and disabled is invalid ");}

}

Private void btnsend_click (Object sender, system. eventargs E)

{

Try

{

String strsend = "server --->" + rtbsend. Text + "\ r \ n ";

Byte [] bytesend = encoding. bigendianunicode. getbytes (strsend );

Mysocket. Send (bytesend, bytesend. length, 0 );

}

Catch {MessageBox. Show ("the connection has not been established and cannot be sent .");}

}

Private void form1_closing (Object sender, system. componentmodel. canceleventargs E)

{

Try

{

Listeningsocket. Close (); // close the scoket connection and release all associated resources before closing the window.

}

Catch {}

}

}

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.