C#のsocket Communication

Source: Internet
Author: User



Bo mainly to do a mobile phone and computer-side (C #) communication program, the network of things related to the socket. But the receipt of the file is stuck, how also received incomplete. Later do a shard processing, if the Shard, send when there will be a different socket (client development is not me, so I can not control how people hair), the results hit the mountains.



Because of the sending time for the loop hair, resulting in not having a heavy frame is lost, it has been deeply researched.



1.Socket



The socket includes the IP address and the port number, the program communicates through the socket, and the socket is equivalent to a component of the operating system. A socket is a communication mechanism between processes, often referred to as a "socket," which describes the IP address and port number, and is a handle to a communication chain. To put it bluntly, it is two programs for communication.



A deeper understanding of the reference to a colleague's blog: http://blog.csdn.net/jiajia4336/article/details/8798421



Life Case Comparison:



The communication between sockets can be analogous to the case of phone calls in life. Any user before the call, the first to occupy a telephone, equivalent to apply for a socket, but also to know the other person's number, the equivalent of a fixed socket, and then dial the caller, the equivalent of making a connection request. If the other party is present and free, pick up the telephone handset and the two sides can make a call. The two sides of the call process, is the direction of the telephone signal and the other side from the telephone to receive the signal process, the equivalent of sending data to the socket and receiving data from the socket. After the call ends, one side hangs up the phone, which is the equivalent of closing the socket and revoking the connection.



Note: The socket can communicate not only between two computers, but also between two programs on the same computer.



2, Port advanced (in-depth)



Port number range: 0-65535, which can represent a total of 65,536 numbers.



by port number can be divided into 3 Big class



(1) Recognized ports (wellknownports): from 0 to 1023, they are tightly bound (binding) to some services. Usually the communication of these ports clearly indicates the protocol of a certain service. For example: Port 80 is actually always HTTP traffic.



(2) Registration port (registeredports): from 1024 to 49151. They are loosely tied to some services. This means that there are many services bound to these ports, which are also used for many other purposes. For example: Many systems handle dynamic ports starting around 1024.



(3) dynamic and/or private ports (dynamicand/orprivateports): from 49152 to 65535. In theory, these ports should not be assigned to the service. In fact, machines typically allocate dynamic ports from 1024 onwards.



Once a computer in the network is identified by an IP address, there may be many applications on the computer that provide services, each of which corresponds to a port.



There are many such hosts on the internet, which typically run multiple service software while providing several services, each of which opens a socket and binds to a port with different ports corresponding to different services (applications)



For example: HTTP using port 80, FTP using 21 port SMTP using 25 port



3.Socket classification



There are two main types of sockets:


    1. Streaming sockets


is a connection-oriented socket that is secure, but inefficient, for connection-oriented TCP service applications



2, data-report socket



is a non-connected socket that corresponds to a non-connected UDP service application that is unsafe but highly efficient



4. Socket general Application Mode (server side and client)



Server-side sockets (minimum of two required)



01. One is responsible for receiving client connection requests (but is not responsible for communicating with the client)



02. Every successful connection to the client generates a socket for the corresponding complex communication on the server side.



021. Created when a client connection is received



022. Create a corresponding socket on the server side for each successful client request (responsible for communicating with the client)



Socket for Client


    1. You must specify the server address and port to connect to
    2. Initializes a server-side TCP connection by creating a socket object





Through, we can see, the first server will create a listener responsible for the socket, and then the client through the socket connection to the server designated port, the end of the server is responsible for monitoring the socket, monitoring the client has a connection, create a responsible and client communication socket.



Let's look at the more specific communication process for the socket:



The communication process of the socket



Server-side:



01, apply for a socket



02, bound to an IP address and on a port



03, turn on Listen, wait for receive connection



Client:



01, apply for a socket



02, Connection server (indicates IP address and port number)



After the server receives the connection request, a new socket (port greater than 1024) is created to connect with the client and communicates, and the original listener socket continues to listen.



Note: The socket responsible for communication cannot be created indefinitely, and the number created is related to the operating system.



Constructors for 5.Socket



Public Socket (addressfamily addressfamily,sockettype sockettype,protocoltype protocoltype)



AddressFamily: Specifies the addressing scheme that the socket uses to resolve addresses. For example: internetwork Indicates when the socket is connected using an IP version 4 address



SocketType: Defines the type of socket to open



The socket class uses the ProtocolType enumeration to notify the Windows Sockets API of the requested protocol



Attention:



1, the port number must be between 1 and 65535, preferably after 1024.



2, the remote host to be connected must be listening on the specified port, that is, you are not free to connect to the remote host.



Such as:



IPAddress addr = Ipaddress.parse ("127.0.0.1");



IPEndPoint ENDP = new IPEndPoint (addr,,9000);



Server binding First: Serverwelcomesocket.bind (ENDP)



Client reconnection: Clientsocket.connect (ENDP)



3, one socket can only connect one host at a time



4,socket cannot be used again after closing



5, each socket object can be connected to only one remote host. If you want to connect to more than one remote host, you must create multiple socket objects.



6.Socket Common Classes and methods



Related classes:



IPAddress: contains an IP address



IPEndPoint: Contains a pair of IP addresses and port numbers



Method:



Socket (): Create a socket



Bind (): Binds a local IP and port number (IPEndPoint)



Listen (): Let the socket listen for incoming connections eat that disease and specify the listening queue capacity



Connect (): Initialize the connection to another socket



Accept (): Receive the connection and return a new socket



Send (): Output data to socket



Receive (): reading data from the socket



Close (): Close socket, destroy connection



7. Socket Reception



Bloggers are because some of the online bad code and ideas have been pits a lot of time, so deliberately explained.



Receive buffers for sockets



We all know that the socket receiver method makes the receive,receive is read from the socket buffer, the socket buffer is a dynamic thing, you read one, is equivalent to processing one, on the reduction of one.



The meaning of this buffer: the data that is currently received, which means that the data within the time you read it, can be increased over time.



We can understand that as a queue, the sender adds data to the queue, and the receive takes the data.



Socket receives data



This buffer in Windows limits the size to 8k, so we can accept up to 8k of data, and if we process too slowly and exceed the sender's time-out, the sender will show a timeout. Therefore, synchronous processing requires us to read in time. Otherwise, either asynchronously, or another thread processing.



Of course, if we both agree on the size of the message, such as 1k, then we can read 1024 bytes each time we accept it.



The point is, if we want to read a file, the sender uses a single socket send, then we can only read one byte at a time (the contract is even can read 2, contract 4 or 8 multiples, can read 4 or 8), buffer data is arrived in order.



After reading, we re-assemble the message, then parse the file field and revert to the file.



Another: If the file is too large, after slicing, non-stop new socket send is not advisable, you can try to send the same socket (Bo Master not verified)



The code I received on the previous paragraph:





private void ServerStart ()
        {
            // Create IPEndPoint instance
            IPEndPoint ipep = new IPEndPoint (IPAddress.Any, Port);
            // Create a socket
            serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            // Bind the created socket to IPEndPoint
            serverSocket.Bind (ipep);
            // Set the socket to listen to Listen mode
            serverSocket.Listen (9999);

            while (true)
            {
                try
                {
                    // Receive incoming connection on socket
                    Socket acceptSocket = serverSocket.Accept ();
                    if (acceptSocket! = null)
                    {
                        Thread socketConnectedThread = new Thread (ReceiveData);
                        socketConnectedThread.IsBackground = true;
                        socketConnectedThread.Start (acceptSocket);

                        //ThreadPool.SetMinThreads(100, 100);
                        //ThreadPool.QueueUserWorkItem(new WaitCallback (ReceiveData), acceptSocket);

                        Dispatcher.BeginInvoke ((Action) (() => {

                            richTextBox.AppendText ("\ nThere is client access ...");

                        }));

                    }

                }
                catch (Exception ex)
                {
                    MessageBox.Show ("listening Error:" + ex.Message);
                }
            }
        }

        private void ReceiveData (object obj)
        {
            Socket s = (Socket) obj;
            // Send information to the client based on the listening client socket
            IPEndPoint clientep = (IPEndPoint) s.RemoteEndPoint;

            try
            {
                List <byte> list = new List <byte> ();
                byte [] buffer = new byte [1];
                int readBytes = 0;
                do
                {
                    readBytes = s.Receive (buffer, 0, buffer.Length, SocketFlags.None);
                    list.AddRange (buffer);
                }
                while (s.Available! = 0);
                byte [] buffers = list.ToArray ();

                Dispatcher.BeginInvoke ((Action) (() =>
                {
                    richTextBox.AppendText ("\ nIP address:" + clientep.Address + "port number:" + clientep.Port);
                }));

                byte [] messageBuffer = new byte [list.Count-8];
                messageBuffer = buffers.Skip (8) .Take (list.Count-8) .ToArray ();
                Message receive = MessageHelp.DeSerialize (messageBuffer);
                if (receive! = null)
                {
                    switch (receive.messageType)
                    {
                        case "link":
                            ClientIp = receive.sourceIp;
                            ClientPort = Convert.ToInt32 (receive.sourcePort);

                            // Send ok after receiving
                            byte [] sendData = MessageHelp.Serialize (new Message {messageType = "link", sourceIp = LocalIpAddress, sourcePort = Port.ToString (), content = "ok"});
                            //s.Send(sendData, sendData.Length, SocketFlags.None);

                            Socket toClient = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            toClient.Connect (new IPEndPoint (IPAddress.Parse (ClientIp), ClientPort)); // Connect to this IP address
                            toClient.Send (sendData, sendData.Length, SocketFlags.None);

                            break;
                        case "command":

                            byte [] responseData = MessageHelp.Serialize (new Message {messageType = "command", sourceIp = LocalIpAddress, sourcePort = Port.ToString (), content = receive.content});
                            Socket reClient = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                            reClient.Connect (new IPEndPoint (IPAddress.Parse (ClientIp), ClientPort)); // Connect with this IP address
                            reClient.Send (responseData, responseData.Length, SocketFlags.None);

                            Dispatcher.BeginInvoke ((Action) (() =>
                            {
                                richTextBox.AppendText ("\ n" + receive.content);
                            }));
                            break;

                        case "file":

                            FileName = receive.fileName;
                            byte [] csharpFileByte = new byte [receive.fileTotalLength];

                            for (int i = 0; i <receive.bytes.Length; i ++)
                            {
                                csharpFileByte [i] = Convert.ToByte (receive.bytes [i] & 0xff);
                            }

                            System.IO.File.WriteAllBytes (FileName, csharpFileByte);
                            MessageBox.Show ("File received successfully");

                            // Send ok after receiving
                            byte [] responseFile = MessageHelp.Serialize (new Message {messageType = "file", sourceIp = LocalIpAddress, sourcePort = Port.ToString (), content = receive.content});
                             //s.Send(sendData, sendData.Length, SocketFlags.None);

                             Socket fClient = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                             fClient.Connect (new IPEndPoint (IPAddress.Parse (ClientIp), ClientPort)); // Connect with this IP address
                             fClient.Send (responseFile, responseFile.Length, SocketFlags.None);
                             break;
                     }
                 }

                 }
                 catch (Exception ex)
                 {
                     s.Close ();
                 }
             s.Close ();
             s.Dispose ();
         }





C#のsocket Communication


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.