C # Socket programming notes

Source: Internet
Author: User

Are you familiar with this question? Search in the blog garden to find that there are too many articles on this topic ~~~ There is really no need to write, and I am a little too lazy to think about words. (If you see this, you must have a turning point. Otherwise, you won't be able to see the following, will you?) but for your reference, it is necessary to add basic socket knowledge first.

Note: If you have been in touch with the socket, there is no need to delay reading. In addition, if you find any errors, please note them directly.

1. Introduce socket first by Convention
Many things in Windows are borrowed from the Unix field, and the Socket is the same. In Unix, socket represents a file descriptor (in Unix, everything is in file units), which is used to describe network access. What does it mean? That is, programmers can send and receive data on the network through socket. You can also understand it as an API. With this interface, you do not need to directly operate the network card, but use this interface to save a lot of complicated operations.

In C #, MS provides System. Net. Sockets
The namespace that contains the Socket class.

2. With socket, you can use it to access the network.

But don't be too happy. to access the network, you have to have some basic conditions (I won't mention anything unrelated to programming):.
To determine the IP address and port of the local machine, the socket can exert its powerful power only when it is bound to a certain IP address and port. B.
You have to have a protocol (otherwise, who would recognize what you sent to the network ). We can decide the protocol for the sake of complexity. However, this is not mentioned in this Article. Here I will introduce the two most familiar protocols: TCP
& UDP. (Don't say you don't know, or... I won't tell you)

If you have the basic conditions, you can use them to access the network. Let's take a look at the steps:
A. Create a socket
B.
Bind the IP address and port of the Local Machine
C.
If it is TCP, because it is connection-oriented, you need to use the ListenO () method to monitor whether someone sends something to yourself on the network; if it is UDP, because there is no connection, so the visitor does not refuse.

D.
In TCP, if a connection is monitored, you can use accept to Receive the connection, and then you can use Send/Receive to perform the operation. However, UDP does not require accept,
Directly use SendTo/ReceiveFrom to perform the operation. (See clearly. It is different from the TCP execution method. Because UDP does not need to establish a connection, you do not know the IP address and port of the other party before sending the message, therefore, you must specify a sending node for normal sending and receiving)

E. Do not waste resources if you do not want to send or receive messages. Close if you can.
If you have read the text above and you are not clear about it, let's take a look at the figure:

Connection-oriented Socket System Call Sequence

 

Time series of connectionless socket system calls

 


3. Start typing ~~ Code (simple code)
First, let's write a connection-oriented

 

TCPServer
Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;

Namespace tcpserver
{
/// <Summary>
/// Summary of Class1.
/// </Summary>
Class server
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Staticvoid Main (string [] args)
{
//
// TODO: Add code here to start the application
//
Int recv; // indicates the length of information sent by the client.
Byte [] data = newbyte [1024]; // used to cache the information sent by the client. The information transmitted through the socket must be a byte array
IPEndPoint ipep = new IPEndPoint (IPAddress. Any, 9050); // the IP address and port pre-used by the Local Machine
Socket newsock = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Newsock. Bind (ipep); // Bind
Newsock. Listen (10); // Listen
Console. WriteLine ("waiting for a client ");
Socket client = newsock. Accept (); // execute when an available client connection attempts and return a new socket for communication with the client
IPEndPoint clientip = (IPEndPoint) client. RemoteEndPoint;
Console. WriteLine ("connect with client:" + clientip. Address + "at port:" + clientip. Port );
String welcome = "welcome here! ";
Data = Encoding. ASCII. GetBytes (welcome );
Client. Send (data, data. Length, SocketFlags. None); // Send information
While (true)
{// Uses an endless loop to continuously obtain information from the client
Data = newbyte [2, 1024];
Recv = client. Receive (data );
Console. WriteLine ("recv =" + recv );
If (recv = 0) // when the information length is 0, the client is disconnected.
Break;
Console. WriteLine (Encoding. ASCII. GetString (data, 0, recv ));
Client. Send (data, recv, SocketFlags. None );
}
Console. WriteLine ("Disconnected from" + clientip. Address );
Client. Close ();
Newsock. Close ();

}
}
}

 

TCPClient
Using System;
Using System. Net;
Using System. Net. Sockets;
Using System. Text;

Namespace tcpclient
{
/// <Summary>
/// Summary of Class1.
/// </Summary>
Class client
{
/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Staticvoid Main (string [] args)
{
//
// TODO: Add code here to start the application
//
Byte [] data = newbyte [1024];
Socket newclient = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Console. Write ("please input the server ip :");
String ipadd = Console. ReadLine ();
Console. WriteLine ();
Console. Write ("please input the server port :");
Int port = Convert. ToInt32 (Console. ReadLine ());
IPEndPoint ie = new IPEndPoint (IPAddress. Parse (ipadd), port); // server IP address and port
Try
{
// Because the client is only used to send information to a specific server, you do not need to bind the local IP address and port. You do not need to listen.
Newclient. Connect (ie );
}
Catch (SocketException e)
{
Console. WriteLine ("unable to connect to server ");
Console. WriteLine (e. ToString ());
Return;
}
Int recv = newclient. Receive (data );
String stringdata = Encoding. ASCII. GetString (data, 0, recv );
Console. WriteLine (stringdata );
While (true)
{
String input = Console. ReadLine ();
If (input = "exit ")
Break;
Newclient. Send (Encoding. ASCII. GetBytes (input ));
Data = newbyte [2, 1024];
Recv = newclient. Receive (data );
Stringdata = Encoding. ASCII. GetString (data, 0, recv );
Console. WriteLine (stringdata );
}
Console. WriteLine ("disconnect from sercer ");
Newclient. Shutdown (SocketShutdown. Both );
Newclient. Close ();

}
}
}

The following is a connectionless example (it's too lazy, and the following is a direct copy of another user)

 

UDPServer
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Net;
Using System. Net. Sockets;
Namespace SimpleUdpSrvr
{
Class Program
{
Staticvoid Main (string [] args)
{
Int recv;
Byte [] data = newbyte [1024];
IPEndPoint ipep = new IPEndPoint (IPAddress. Any, 9050); // define a network endpoint
Socket newsock = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp); // define a Socket
Newsock. Bind (ipep); // The Socket is associated with a local endpoint.
Console. WriteLine ("Waiting for a client ..");

IPEndPoint sender = new IPEndPoint (IPAddress. Any, 0); // defines the address of the computer to be sent.
EndPoint Remote = (EndPoint) (sender );//
Recv = newsock. ReceiveFrom (data, ref Remote); // accept data
Console. WriteLine ("Message received ed from {0}:", Remote. ToString ());
Console. WriteLine (Encoding. ASCII. GetBytes (data, 0, recv ));

String welcome = "Welcome to my test server! ";
Data = Encoding. ASCII. GetBytes (welcome );
Newsock. SendTo (data, data. Length, SocketFlags. None, Remote );
While (true)
{
Data = newbyte [2, 1024];
Recv = newsock. ReceiveFrom (data, ref Remote );
Console. WriteLine (Encoding. ASCII. GetString (data, 0, recv ));
Newsock. SendTo (data, recv, SocketFlags. None, Remote );
}
}
}
}

 

UDPClient
Using System;
Using System. Collections. Generic;
Using System. Text;
Using System. Net;
Using System. Net. Sockets;
Namespace SimpleUdpClient
{
Class Program
{
Staticvoid Main (string [] args)
{
Byte [] data = newbyte [1024]; // defines an array for data buffer.
String input, stringData;
IPEndPoint ipep = new IPEndPoint (IPAddress. Parse ("127.0.0.1"), 9050 );
Socket server = new Socket (AddressFamily. InterNetwork, SocketType. Dgram, ProtocolType. Udp );
String welcome = "Hello, are you there? ";
Data = Encoding. ASCII. GetBytes (welcome );
Server. SendTo (data, data. Length, SocketFlags. None, ipep); // send data to the specified endpoint

IPEndPoint sender = new IPEndPoint (IPAddress. Any, 0 );
EndPoint Remote = (EndPoint) sender;
Data = newbyte [2, 1024];
Int recv = server. ReceiveFrom (data, ref Remote); // receives data from the server.

Console. WriteLine ("Message received ed from {0}:", Remote. ToString ());
Console. WriteLine (Encoding. ASCII. GetString (data, 0, recv ));
While (true) // read data
{
Input = Console. ReadLine (); // read data from the keyboard
If (input = "text") // end mark
{
Break;
}
Server. SendTo (Encoding. ASCII. GetBytes (input), Remote); // send data to the specified endpoint Remote
Data = newbyte [2, 1024];
Recv = server. ReceiveFrom (data, ref Remote); // receives data from Remote
StringData = Encoding. ASCII. GetString (data, 0, recv );
Console. WriteLine (stringData );
}
Console. WriteLine ("Stopping client ");
Server. Close ();
}
}
}

 

The preceding example simply uses socket to implement communication. You can also implement asynchronous socket and IP multicast.

MS also provides several helper classes: TcpClient, TcpListener, and UDPClient. These classes simplify some operations, so you can also use these classes to write the code, but I personally prefer to directly use socket to write.

Now that I have finished writing, I will say a few more words. In the software that requires instant response, I personally prefer to use UDP for communication, because compared with TCP, UDP consumes less resources and has fast response speed and low latency. As for the reliability of UDP, it can be achieved through control at the application layer. Of course, TCP is recommended in environments with high reliability requirements.

Http://www.cnblogs.com/stg609/archive/2008/11/15/1333889.html

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.