C #. Net synchronous asynchronous socket communication and multithreading summary)

Source: Internet
Author: User
C #. Net synchronous asynchronous socket communication and multithreading Summary

Source: http://www.cnblogs.com/Silverlight_Team/archive/2009/03/13/1411136.html

Synchronous socket communication

Point-to-point online communication supported by socket

The server monitors connections, and the client sends connection requests. After a connection is established, the client sends and receives data.

The server establishes a socket, sets the local IP address and listening port to bind with the socket, and starts listening for connection requests. After receiving the connection request, the server sends a confirmation message to establish a connection with the client, start to communicate with the client.

The client establishes a socket, sets the IP address of the server and the port that provides the service, sends a connection request, receives the confirmation of the service, tries its best to connect, and starts to communicate with the server.

The connection between the server and the client and the data transmission between them are both synchronized.

Socket

Socket is a TCP/IP network protocol interface. Many functions and routines are defined internally. It can be seen as an endpoint of network communication. Two hosts or two processes are required for network communication. Transmit data through the network,ProgramEach end of the network conversation requires a socket.

The TCP/IP transport layer uses the protocol port to transmit data to a specific application of a host. The protocol port is the process address of an application. The network software module of the transport layer module needs to communicate with another program. It uses the protocol port, and the socket is an API running on the transport layer, to send data through a socket connection, you must specify a port for it.

Socket:

Stream socket provides bidirectional, ordered, and non-repetitive data stream services, allowing you to slide a large amount of network data.

The dgram socket data PACKET socket supports two-way data streams, which does not guarantee reliable, orderly, and non-duplicated transmission.

Row socket original socket access underlying protocol

Establish a socket using C #

Namespace: using system. Net; using system. net. Socket;

Create a new socket object: Socket prototype:

Public socket (addressfamily, sockettype, protocoltype)

Addressfamily is used to specify the addressing scheme of the socket resolution address. Inte. Network indicates the address of IP version 4, and inte. networkv6 requires the address of IP version 6.

The sockettype parameter specifies that the socket type raw supports basic transmission protocol access. Stream supports reliable, bidirectional, and connection-based data streams.

Protocoltype indicates the network protocol supported by socket

Define host objects:

Ipendpoint class: ipendpoint construction method location: system. net

Prototype: 1) Public ipendpoint (IPaddress address, int port) 2) Public ipendpoint (Long Address, int port) parameter 1 integer int64, such as 123456, parameter 2 port int32

Host Resolution:

Use the DNS server to resolve hosts and use the DNS. Resolve Method

Prototype: public static iphostentry resolve (string hostname) parameter: name of the host to be parsed. The iphostentry class value is returned, and iphostentry is inte.. Net host address information provides a container that contains a list of IP addresses and host names.

DNS. gethostbyname get the local host name

Prototype: public static iphostentry gethostbyname (string hostname)

Gethostbyaddress

Prototype: 1) public static iphostentry gethostbyaddress (IPaddress Address) parameter: IP address 2) public static iphostentry gethostbyaddress (string address) ip address Format String

Port binding and listening:

Synchronous socket server host binding and port listening

BIND (host bound), listen (listening port), and accept (receiving client connection requests) of the socket class)

BIND: Prototype: Public void BIND (endpoint localep) parameter is the host object ipendpoint

Listen: Prototype: integer value of the public void listen (INT backlog) parameter, maximum value of the suspended queue

Accept: Prototype: Public socket accept () return as a socket object

Demo program:

IPaddress myip = IPaddress. parse ("127.0.0.1 ");

Ipendpoint myserver = new ipendpoint (myip, 2020 );

Socket sock = new socket (addressfamily. inte. Network, sockettype. Stream, protocoltype. TCP );

Sock. BIND (myserver );

Sock. Listen (50 );

Socket BBB = sock. Accept ();

Send data: Method 1: socket-class send method 2. networkstream-class write

Send prototype: Public int send (byte [] buffer) byte array

Public int send (byte [], socketflags) Prototype 2 Description, socketflags member list: dontroute (do not use route table to send), maxiovectorlength (provides the standard value for the number of wsabuf structures that send and receive data) none indicates the use of a flag for the next call.) outofband (sending or receiving part of the message) partial (sending or receiving part of the message) PEEK (viewing the incoming message)

Prototype 3: Public int send (byte [], Int, socketflags) parameter 2 number of bytes to be sent

Prototype 4: Public int send (byte [], Int, Int, socketflags) parameter 2: the start position of the byte []

Demo:

Socket BBB = sock. Accept ();

Byte [] bytes = new byte [64];

String send = "aaaaaaaaaaaa ";

Bytes = system. Text. encoding. bigendianunicode. getbytes (send. tochararray ());

Bbb. Send (bytes, bytes. length, 0); // send all the byte Arrays

The write method of the. networdstream class sends data.

Prototype: Public override void write (byte [] buffer, int offset, int size) byte array, starting byte location, Total Bytes

Socket BBB = sock. Accept ();

. Networkstream stre = new newworkstream (BBB );

Byte [] CCC = new byte [1, 512];

String sendmessage = "aaaaaaaaaaaaaa ";

CCC = system. Text. encoding. bigendianunicode. getbytes (sendmessage );

Stre. Write (CCC, 0, CCC. Length );

Receive data: Socket class receive. networkstream class read

Socket-class receive Method

Prototype: Public int receive (byte [] buffer)

2) Public int receive (byte [], socketflags)

3) Public int receive (byte [], Int, socketflags)

4) Public int receive (byte [], Int, Int, socketflags)

.....

Socket BBB = sock. Accept ();

........

Byte [] CCC = new byte [1, 512];

Bbb. Receive (CCC, CCC. length, 0 );

String rece = system. Text. encoding. bigendianunicode. getstring (CCC );

Richtextbox1.appendtext (RECE + "\ r \ n ");

The read method of the. networkstream class receives data.

Public override int read (INT byte [] buffer, int offset, int size)

Demo: BBB = sock. Accept ();

.......

. Networkstream stre = new. networkstream (BBB );

Byte [] CCC = new byte [1, 512];

Stre. Read (CCC, 0, CCC. Length );

String readmessage = system. Text. encoding. bigendianunicode. getstring (CCC );

Thread

Thread creation: the Thread class construction method in the system. Threading space:

Prototype: Public thread (threadstart start) threadstart type value

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

Private void ACCP () {}// use a thread

Thread startup

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

Thread pause and restart

Start the thread to use thread. sleep indicates that the current thread is blocked for a period of time. sleep (timeout. infinite) is the thread sleep until it is called thread. another thread of interrrupt is interrupted or is interrupted by the thread. abort abort.

One thread cannot call sleep for another. You can use thread. suspend to suspend the thread when the thread calls the thread for itself. suspend will be blocked until the thread is resumed by another thread. When one thread calls another, the call will become a non-blocking call that suspends the other thread. The call of thread. Resume causes another thread to jump out of the pending state and the thread to continue execution, regardless of the number of calls of thread. Suspend.

Thread sleep: thread. Sleep (10000 );

Thread suspension: thread = new thread (New threadstart (ACCP ));

Thread. Start ();

Thread. Suspend ();

Restart: thread = new thread (New threadstart (ACCP ));

Thread. Start ();

Thread. Suspend ();

Thread. Resume ();

Thread blocking method: thread. Join uses one thread to wait for another thread to stop.

Thread. Join

Public void join ();

Public void join (INT millisecondstimeout); millisecond

Public bool join (timespan timeout); Time Interval Type Value

Instance: thread = new thread (New threadstart (ACCP ));

Thread. Start ();

Thread. Join (1, 10000 );

Thread destruction:

Thread. Abort, thread. Interrupt

The abort method triggers threadabortexception and starts to abort this thread.CodeFor special exceptions captured, resetabort can cancel the abort request and organize threadabortexception to terminate this thread. The thread may not be terminated immediately and will not be terminated at all.

If you call abort for a thread that has not been started, the thread stops when you call start. If you call abort for a suspended thread, the thread continues and stops. If you call abort for a blocked or sleep thread, the thread is interrupted and then terminated.

The abort method of the thread class:

Public void abort ()

Public void abort (Object stateinfo );

Demo:

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

Thread. Start ();

Thread. Abort ();

Thread. Join (1, 10000 );

Socket programming principle:

Unix I/O command set. The mode is on-read/write-off open write/read close.

User processes perform I/O operations

A user process calls the open command to obtain the right to use a file or device, and returns an integer of the description file or device to describe the process opened by the user. The process performs read/write operations and transmits data, the operation is complete and the process is closed, notifying the OS of the object to be used.

UNIX Network Application Programming: BSD Socket socket, UNIX System v tli.

Basic concepts of socket programming:

Inter-network process communication: it is originated from a single-host system. Each process runs within its own address range to ensure mutual interference and coordination. The operating system provides facilities for communication between processes:

Unix bsd pipeline pipe, named pipeline Named Pipe Soft Interrupt signal

UNIX System V message shared storage zone shared memory semaphore

The preceding steps are only applicable to communication between local processes.

Port: a communication port that can be named and addressable on the network. It is a resource that can be allocated by the operating system. The final address of network communication is not the host address, is a identifier that describes a process. TCP/IP proposes the protocol port porotocol port to indicate the communication process.

The process binds the connection port through the OS call, and transmits the data transmitted to the port to the process in the transport layer for processing. The data also needs to be transferred to the transport layer through the binding port. The process operates on the port equivalent to operating on the I/O file in the OS. Each port also corresponds to a port number. The TCP/IP protocol is divided into TCP and UDP, although there are ports with the same port number, they do not conflict with each other. The port number is allocated globally and locally (dynamically). When a process needs to access the transport layer, the OS assigns a port number to the process. Global Allocation refers to the fixed port allocated by the OS. Standard servers all have fixed globally recognized port numbers for the service. A port smaller than 256 can be used as a reserved port.

Address: two machines in the network communication can be no longer in the same network, and may be separated (gateway, bridge, router, etc.), so they can be divided into three layers of addressing

The machine has a specific ID of the network in different networks.

Machines in the same network should have a unique machine ID

Processes in a machine should have their own unique ID

Generally, the host address = network ID + host ID TCP/IP uses a 16-bit port number to represent the process.

Network byte order, high-price first storage, TCP and UDP both use 16 or 32 full-digit high-price storage, in the header file of the Protocol.

Semi-correlation: a process in the network is a protocol + local address + port number = triple, also called semi-correlation, indicating half.

Full correlation: the same protocol is required for communication between two machines.

Protocol + local address + local port number + remote address + remote port number, all five groups are related.

Sequence: two consecutive packets may not arrive through the same path in the network, so the receiving sequence is inconsistent with the sending sequence. The order is the same as the sending order. TCP/IP provides this function.

Error Control: check data errors: Check and checksum mechanism check connection errors: both parties confirm the response mechanism.

Throttling: This mechanism ensures the data transmission rate during data transmission and prevents data loss.

Byte stream: Uses transmitted packets as a byte sequence without any data boundary.

Full/half duplex: either sending in two directions or sending in one direction

Cache/out-of-band data: In the byte stream service, data of any length can be read at the same time without message boundaries. To ensure correct transmission or stream Protocol control, cache is required. cached applications disable caching.

A type of information that you want to process in a timely manner without passing through the conventional transmission mode (delete, control-C of the UNIX System) the terminal stream control operator control-s and control-q) is out-of-band data.

Customer/Server mode active request method:

1. Open a communication channel to notify the local host to receive customer requests at a recognized address

2. Wait for the customer request to arrive at the port

3. Receive duplicate service requests and process the requests to send response signals. Receives concurrent service requests. To activate a new process to process customer requests, the UNIX system fork and exec. The new process processes customer requests and does not need to respond to other requests. After the service is completed, disable the communication link between the Process and the customer. Termination

4. Return step 2, waiting for another customer's request.

5. Disable the server

Customer:

1. Open a channel and connect to the specific port of the host where the server is located.

2. Send the service request message to the server, wait for and receive the response; Continue to make the request .......

3. Close and terminate the communication channel after the request ends.

:

1. The role of client and server processes is asymmetric, with different codes

2. The service process is started prior to the customer's request. The system runs and the service process exists until it Exits normally or forcibly.

Socket Type:

TCP/IP socket

Sock_stream reliably transmits connection data without errors or repeated sending. It sends and receives data in an ordered manner and provides traffic control to avoid data flow exceeding the limit. The data is a byte stream with no length limit, ftp stream socket.

Sock_dgram is a connectionless service. data packets are sent in the form of independent packets, without any guarantee. data may be lost and duplicated, and the sending and receiving order is disordered. Network File System NFS uses a datagram socket.

The sock_ram interface allows direct access from lower-layer protocols, IP addresses, and ICMP, and checks for new protocol implementations or accesses new devices configured in existing services.

Server:

Using system. net;

Using system. net. Sockets;

Using system. text;

Using system. Threading;

Thread mythread;

Socket socket;

// Clear all resources in use.

Protected override void dispose (bool disposing)

{

Try

{

Socket. Close (); // release resources

Mythread. Abort (); // abort a thread

}

Catch {}

If (disposing)

{

If (components! = NULL)

{

Components. Dispose ();

}

}

Base. Dispose (disposing );

}

Public static IPaddress getserverip ()

{

Iphostentry IEH = DNS. gethostbyname (DNS. gethostname ());

Return IEH. Addresslist [0];

}

Private void beginlisten ()

{

IPaddress serverip = getserverip ();

Ipendpoint IEP = new ipendpoint (serverip, 8000 );

Socket = new

Socket (addressfamily. inte. Network, sockettype. Stream, protocoltype. TCP );

Byte [] bytemessage = new byte [1, 100];

This. label1.text = IEP. tostring ();

Socket. BIND (IEP );

// Do

While (true)

{

Try

{

Socket. Listen (5 );

Socket newsocket = socket. Accept ();

Newsocket. Receive (bytemessage );

String stime = datetime. Now. tow.timestring ();

String MSG = stime + ":" + "Message from :";

MSG + = newsocket. remoteendpoint. tostring () + encoding. Default. getstring (bytemessage );

This. listbox1.items. Add (MSG );

}

Catch (socketexception ex)

{

This. label1.text + = ex. tostring ();

}

}

// While (bytemessage! = NULL );

}

// Start listening

Private void button#click (Object sender, system. eventargs E)

{

Try

{

Mythread = new thread (New threadstart (beginlisten ));

Mythread. Start ();

}

Catch (system. Exception ER)

{

MessageBox. Show (ER. message, "finished", messageboxbuttons. OK, messageboxicon. Stop );

}

}

Client:

Using system. net;

Using system. net. Sockets;

Using system. text;

Private void button#click (Object sender, system. eventargs E)

{

Beginsend ();

}

Private void beginsend ()

{

String ipdomainthis.txt IP. text;

String portdeskthis.txt port. text;

IPaddress serverip = IPaddress. parse (IP );

Int SERVERPORT = convert. toint32 (port );

Ipendpoint IEP = new ipendpoint (serverip, SERVERPORT );

Byte [] bytemessage;

// Do

//{

Socket socket = new socket (addressfamily. inte. Network, sockettype. Stream, protocoltype. TCP );

Socket. Connect (IEP );

Bytemessage = encoding. ASCII. getbytes (textbox1.text );

Socket. Send (bytemessage );

Socket. Shutdown (socketshutdown. Both );

Socket. Close ();

//}

// While (bytemessage! = NULL );

}

Transmission and receiving end based on TCP protocol

Related Article

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.