Project summary--simple and simple socket network programming

Source: Internet
Author: User
Preface:

Why there is the concept of the title, I would like to have not actively heard of the socket network programming people to read the topic may have been blindfolded, in order to well let everyone into the scene, first of all to say a need to use this thing business needs.

First of all, we should be clear that the socket network programming is based on the CS model, such as the computer room fee system, in the computer room fee system may encounter different computer room use of the charging system is the use of the same database. However, for some of the displayed information, you can only update to the form every time you query the database. Take the simplest main interface of the current number of machines, there are room A and room B two rooms, and they are using the same database, and then two on duty teachers at the same time work, but the engine room A to increase or reduce the number of people on the machine , the room B teacher on duty is unable to receive the message in real time and update his form. This causes a temporary error in the information displayed by the form. Then we use the socket network programming.

first, the official interpretation of the socket mechanism:

The most common scenario in network programming is the Client/server (client/server) model. In this scenario, the client application requests services from the server program. A service program listens to requests for services at a well-known address, that is, the service process is dormant until a client requests a connection to the address of the service. At this point, the service program is "awakened" and provides service to the customer-respond appropriately to the customer's request.

In order to facilitate this client/server model of network programming, in the early 90, Microsoft joined several other companies to develop a set of Windows network programming interface, that is, the WindowsSockets specification, it is not a network protocol, but a set of open , a network programming interface under Windows that supports multiple protocols. Now the Winsock has basically implemented the Protocol independent, you can use Winsock to invoke the functionality of a variety of protocols, but the more commonly used is the TCP/IP protocol. The socket actually provides a communication port on the computer that can communicate with any computer with a socket interface through this port. The application is transmitted over the network and the received information is implemented through this socket interface.

second, the popular understanding of the socket

We can simply interpret the socket as a conduit between different computer programs on the network, and throw a bunch of data from the end of a pipe, from the B side of the pipe (and perhaps from C, D, E, F ...). End up). The port of the pipe is uniquely identified by two factors, that is, the IP address of the machine and the port number used by the program. The meaning of the IP address everyone knows that the so-called port number is a programmer to specify a number, many well-known Trojan programs all day on the network scan different port number is to obtain a port can be connected to destroy. The more famous port number has HTTP 80 port, of course, we recommend that you write the program do not use too small port number, they are generally occupied by the system, also do not use some well-known ports, generally use 1000~5000 within the port is better.

The socket can support the sending and receiving of data, and it defines a variable called a socket. A socket is first created when the data is sent, and then a ip/port is sent using methods such as send to the socket, and the receiver first creates the socket and then binds the socket to a ip/port. All data sent to this port is read by functions such as the recv of this socket. The same as reading the data in the file.

Third, examples:

Said so much I think we have a simple understanding of the socket, of course, or to the code in depth understanding.

Before looking at the code, but also to do the final explanation, socket programming must use the client and server, although the next example is only one-to-one communication, but in fact, and a one-to-many communication is a principle.

1. Server Code

First look at the server code:

/********************************************************* * Developer: Hanyi * Date Created: 2013/9/27 13:51:48 * Description: Socket network becomes instance server
* Version: 1.0 * All rights reserved: Information Technology accelerated * *******************************************************/using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Net;

Using System.Net.Sockets;
        namespace Server {public partial class Server:form {Socket s = null;
        IPEndPoint IEP = null;
        byte[] buf = new byte[1024];

        Socket worker = null;
            Public server () {InitializeComponent ();
        Control.checkforillegalcrossthreadcalls = false; //Start the server. --Hanyi private void Button1_click_1 (object sender, EventArgs e) {//create a Channel s = new S

            Ocket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); InvasiveBuild a listening point IEP = new IPEndPoint (Ipaddress.any, 20000);

            Bind to channel on S.bind (IEP);
            Listening S.listen (6);
            Through asynchronous processing, open the listening connection, and give the Accept function to handle the connection s.beginaccept (new AsyncCallback (Accept), s);
        This.button1.Visible = false;
            //receives the action of the connection--Hanyi void Accept (IAsyncResult ia) {//Gets the user-defined object that qualifies or contains information about the asynchronous operation. s = ia.
            AsyncState as socket;//This property returns an object that is the last parameter of the method that initiates the asynchronous operation.
            Worker = S.endaccept (IA);//Returns a Socket that handles communication with the remote host.
                S.beginaccept (New AsyncCallback (Accept), s);//re-receive the link and make a callback function try {//start accepting data Worker. BeginReceive (buf, 0, buf.
            Length, Socketflags.none, New AsyncCallback (Receive), worker);
        catch {throw;}
            //Receive Message action--Hanyi void Receive (IAsyncResult ia) {//Get user-defined object that qualifies or contains information about an asynchronous operation. Worker = Ia. AsYncstate as Socket; Gets the data length int count = worker.
            EndReceive (IA);
            Start receiving data yourself. Worker. BeginReceive (buf, 0, buf.
            Length, Socketflags.none, New AsyncCallback (Receive), worker); The data string context = Encoding.GetEncoding ("gb2312") is removed by the GB2312 standard.
            GetString (buf, 0, Count);
            This.textBox1.Text + = Environment.NewLine;
        This.textBox1.Text + = context;  }//Send message-Hanyi private void Button2_click_1 (object sender, EventArgs e) {string context

            = "Admin:" + this.textBox2.Text.Trim (); If (context!= "") {this.textBox1.Text + = environment.newline;//Line Wrap THIS.TEXTB Ox1.
                Text + + context;
                This.textBox2.Text = ""; Worker. Send (encoding.getencoding ("gb2312").
            GetBytes (context));
 }
        }
    }
}

2. Server Interface:

3. Client code

/********************************************************* * Developer: Hanyi * Date Created: 2013/9/27 13:51:48 * Description: Socket network becomes instance client
* Version: 1.0 * All rights reserved: Information Technology accelerated * *******************************************************/using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Net;

Using System.Net.Sockets;
        namespace Client {public partial class Client:form {Socket s = null;
        IPEndPoint IEP = null;

        byte[] buf = new byte[1024];
            Public client () {InitializeComponent ();
        Control.checkforillegalcrossthreadcalls = false; }//Connection server-Hanyi private void Button1_click_1 (object sender, EventArgs e) {s = new Socke
            T (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); IEP = new IPEndPoint (Ipaddress.parse ("127.0.0.1"), 20000);
            try {s.connect (IEP);
            Establish a connection to the remote host This.label1.Text = "successful connection";//Connection success Prompt this.button1.Visible = false;//Hide Connection button
            catch {throw;}
                try {//start receiving connection. S.beginreceive (buf, 0, buf.
            Length, Socketflags.none, New AsyncCallback (Receive), s);
        catch {throw;} //Send message-Hanyi private void Button2_click_1 (object sender, EventArgs e) {St Ring context = IEP.
            ToString () + ":" + This.textBox2.Text.Trim ();
                If (context!= "") {this.textBox1.Text + = Environment.NewLine;
                This.textBox1.Text + = context;
                This.textBox2.Text = ""; Send Message S.send (encoding.getencoding ("gb2312").
            GetBytes (context)); }//Receive Message action--Hanyi void receiVE (IAsyncResult ia) {s = ia.
            AsyncState as Socket;
            int count = S.endreceive (IA); I started to receive data s.beginreceive (buf, 0, buf.
            Length, Socketflags.none, New AsyncCallback (Receive), s); String context = Encoding.GetEncoding ("gb2312").
            GetString (buf, 0, Count);
            This.textBox1.Text + = Environment.NewLine;
        This.textBox1.Text + = context;
 }
    }
}

4. Client interface:

Of course, you will find that this is actually a chat tool, and a friend chat is one-to-one, group chat is a one-to-many. This further helps to understand the meaning of network programming.

Four, Summary:

Through the above code, we can roughly summarize the socket programming several steps: to establish a socket

To create a listening socket on the server side, you can call the socket () function to create the listening socket and define the communication protocol used by the socket. This function call successfully returns the SOCKET object, and the failure returns Invalid_socket

Initialize the calling socket constructor, there are three constructor overloads on MSDN, here we use the third

Sockets (AddressFamily, SocketType, ProtocolType)

Initializes a new instance of the socket class with the specified address family, socket type, and protocol.

Binding ports

The next step is to specify an address and port for this listening socket defined by the server, so that the client knows which port to connect to which address, so we call the bind () function, which returns 0 successfully or returns SOCKET_ERROR. Listening

When a server-side socket object binding completes, the server side must establish a listening queue to receive client connection requests. The Listen () function causes the server-side socket to enter the listening state and set the maximum number of connections that can be established (the current maximum limit is 6 and the minimum value is 1). The function call successfully returns 0, otherwise it returns SOCKET_ERROR. Server-side Accept Client connection request

When the client makes a connection request, the server-side listener window receives a message from the clients that we have customized, at which point we can parse the lparam and call the relevant function to handle the event. In order for the server to accept the client's connection request, it is necessary to use the Accept () function, which creates a socket connected to the client socket, the original listening socket continues to enter the listening state, waiting for other people's connection requirements. The function call successfully returns a newly generated SOCKET object, otherwise it returns Invalid_socket.

the above can be said to be Socket the core content of network programming. It's really not that hard to understand . Special Note: This example is only one-to-one communication, a one-to-many communication or many-to-many communication only a few changes on this basis. This example is just a simple example of a code that needs to be reused to be aware of the naming conventions.

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.