Detailed C # Socket programming Notes _c# Tutorial

Source: Internet
Author: User
Tags readline server port

See this topic, is it very familiar? In the blog Park Search, to ensure that the article about this dongdong is too many ~ ~ ~ really is not written necessary, and I am a bit lazy to ponder words. (see this, must have a turning point, or you will not see the following, no) but, for their next article to write for reference, it is necessary to first add the socket basic knowledge.

Note: If you have contacted the socket, then there is no need to delay the time to watch. Also, if any of these errors are found, please indicate them directly.

1. By convention first to introduce the next socket

Many things in Windows are borrowed from the Unix realm, as are sockets. In Unix, the socket represents a file descriptor (in Unix everything is in a file), and this descriptor is used to describe network access. What does that mean? Is that programmers can send and receive data on the network via a socket. You can also understand it as an API. With it, you do not have to directly operate the network card, but through this interface, which saves a lot of complex operations.

In C #, MS provides us with the System.Net.Sockets namespace, which contains the socket class.

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

But you should not be happy too early, to access the network, there must be some basic conditions (and programming-related I do not mention): A. To determine the IP and port of this computer, the socket can only be powerful if it is bound to an IP and port. B. There must be an agreement (or who will recognize you?) what is sent to the network? To be complicated, we can make our own agreement. But this is not mentioned in this article, I introduce two kinds of people most familiar with the protocol: TCP & UDP. (Don't say you don't know, otherwise ...) Or... I won't tell you.)

If you have the basic conditions, you can start using them to access the network. Let's take a look at the steps:

A. Creating a socket

B. Binding the IP and port of the machine

C. If it is TCP, because it is connection-oriented, use the Listeno () method to monitor whether someone on the network is sending something to themselves;

D. In TCP, if you hear a connection, you can use accept to receive the connection, and then you can use send/receive to perform the operation. UDP, however, does not require accept, and uses sendto/receivefrom directly to perform the operation. (See Well, there is a difference with TCP's execution method, because UDP does not need to establish a connection, so do not know each other's IP and port before sending, so you need to specify a sent node for normal send and receive)

E. If you do not want to continue to send and receive, do not waste resources. Close you can close.

If you look at the above text, you are not clear, then come to see the picture is good:

Connection-oriented socket system call timing

Non-connected socket system call timing

3. Start knocking ~ ~ Code (simple Code)

First, we're going to write a connection-oriented

TCPServer

Using System;
Using System.Net;
Using System.Net.Sockets;

Using System.Text;
  Summary description of namespace TCPServer {///<summary>///Class1.
    </summary> Class Server {///<summary>///application's main entry point.
      </summary> [STAThread] static void Main (string[] args) {///TODO: Add code here to start the application int recv;//is used to indicate the length of information sent by the client byte[] data=new byte[1024];//is used to cache the information sent by the client, and the information passed through the socket must be a byte array ipend Point Ipep=new IPEndPoint (ipaddress.any,9050);//native pre-used IP and port socket newsock=new socket (addressfamily.internetwork,so
       CKETTYPE.STREAM,PROTOCOLTYPE.TCP); Newsock. Bind (IPEP);//Bind Newsock.
       Listen (10);//Monitor Console.WriteLine ("Waiting for a Client"); Socket Client=newsock. Accept ()/////////////////////////////////////////////////////
       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) {///use dead loops to constantly get information from the client data=new byte[1024]; Recv=client.
         Receive (data);
         Console.WriteLine ("recv=" +recv);
         if (recv==0)//When the information length is 0, the client connection disconnects the 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;
  Summary description of namespace TcpClient {///<summary>///Class1.
    </summary> class Client {///<summary>///application's main entry point.
      </summary> [STAThread] static void Main (string[] args) {///TODO: Add code here to start the application
       Byte[] Data=new byte[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's IP and port try {//Because the client is only used to send information to a particular server, the With no need to bind the machine's IP and port.
        No listening is required. 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=new byte[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 given without connection (it is too lazy, the following is a direct copy of others)

Udpserver

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Net;
Using System.Net.Sockets;
       Namespace Simpleudpsrvr {class Program {static void Main (string[] args) {int recv;
       byte[] data = new byte[1024]; IPEndPoint Ipep = new IPEndPoint (Ipaddress.any, 9050);//define a network endpoint Socket Newsock = new Socket (addressfamily.internetwo RK, Sockettype.dgram, PROTOCOLTYPE.UDP);//define a socket newsock.

       Bind (IPEP);//socket associated with a local endpoint Console.WriteLine ("Waiting for a client ..."); IPEndPoint sender = new IPEndPoint (ipaddress.any, 0);//define the address of the computer to be sent EndPoint Remote = (EndPoint) (sender);/RE CV = Newsock.
       ReceiveFrom (data, ref Remote);//Accept Console.WriteLine ("Message Received 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 = new byte[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 {static void Main (string[] args) {byte[] data = new by
       te[1024];//defines a buffer string input, stringdata, that the array uses to make data;
       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 = new byte[1024]; int recv = Server.
       ReceiveFrom (data, ref Remote);//Accept Console.WriteLine from server ("Message received from{0}:", remote.tostring ());
       Console.WriteLine (Encoding.ASCII.GetString (data, 0, recv)); While(true)//read Data {input = Console.ReadLine ()//Read data from keyboard if (input = = "text")/end tag {
         Break } server.
         SendTo (Encoding.ASCII.GetBytes (input), remote);//Send data to the specified endpoint remote data = new byte[1024]; recv = Server.
         ReceiveFrom (data, ref Remote);//from remote to accept StringData = Encoding.ASCII.GetString (0, recv);
       Console.WriteLine (StringData);
       } Console.WriteLine ("Stopping client"); Server.
     Close ();   

 }
   }
 }

The above example simply applies the socket to achieve communication, you can also implement asynchronous socket, IP multicast and so on.

Ms also provides us with a few helper classes: TcpClient class, TcpListener class, UdpClient class. These classes simplify some of the operations, so you can also use these classes to write the above code, but I am personally more accustomed to writing directly with the socket.

Since I'm almost finished, I'll have a few more words to say. In software that requires instant response, I personally prefer to use UDP for communication, because UDP consumes less resources than TCP, and has a fast response and low latency. As for the reliability of UDP, it can be satisfied by controlling in the application layer. Of course, TCP is recommended in environments with high reliability requirements.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.