C # network programming (basic concepts and operations) I

Source: Internet
Author: User

Introduction

C # The Network Programming series will briefly describe the basic knowledge of network programming. Due to my limited skill in this area, I can only provide some preliminary introductory knowledge, I hope to provide some help to my friends who have just started learning. For more details, see related books.

This is the first article in this series. It describes the basic concepts of Network Programming Based on Socket, including three development modes of TCP protocol, Socket, and chat program, there are two basic operations: listening on the port and connecting to the remote server. The second section describes a simple example: transmitting a string from the client to the server, receiving and printing a string from the server, and changing the string to uppercase, then the string is sent back to the client, and the client prints the returned string. The third is an enhancement in the second article, which describes a problem not solved in the second article, asynchronous transmission is used to complete the same functions as the second one. The fourth shows how to send and receive files between the client and the server; article 5 implements a chat program that can chat online and transfer files. It is actually a comprehensive application of previous knowledge.

Basic concepts of network programming 1. connection-oriented transmission protocol: TCP

I don't want to talk too much about the TCP protocol. This is a university course and involves computer science, but I am not an academic school. For this part, I think as a developer, you only need to understand the concepts related to the program, and do not need to study it too hard.

First, we know that TCP isConnection-orientedIt means two remote hosts (or processes, because in fact remote communication is communication between processes, while processes are running programs ), you must perform a handshake to confirm the connection is successful before the actual data can be transmitted. For example, if process A wants to send the string "Its a fine day today" to process B, it must first establish A connection. In this process, it first needs to know the location of process B (host address and port number ). Then we send a request message that does not contain actual data. We can call this message "hello ". If process B receives this "hello", it replies A "hello" to process A, and process a then sends the actual data "Its A fine day today ".

The second thing you need to know about TCP is that it isFull Duplex. It means that if the processes (such as process A and process B) on two hosts establish A connection, data can flow from A to B or B to. In addition, it is stillPoint-to-PointA TCP connection is always between the two. In sending, it is impossible to send data to multiple receivers through a connection. TCP also has a feature calledReliable Data TransmissionAfter the connection is established, the data transmission will surely arrive and be ordered. That is to say, when you send ABC, the receiving party will also receive ABC, instead of BCA or anything else.

One of the most important TCP-related concepts in programming isSocket. We should know the layer-7 network protocol. If we count the above application process, presentation layer, and Session Layer as one layer in general (some textbooks are divided in this way ), the network application program we wrote is located at the application layer, and we all know that TCP is a transport layer protocol, how can we use the transport layer service (message sending or file upload/download) at the application layer )? We all know that in an application, we use interfaces for separation. In the application layer and the transport layer, sockets are used for separation. It is like a small port opened by the transport layer for the application layer. The application sends data remotely or receives data remotely, that is, after the data enters this port, or before the data comes out of this port, we do not know or need to know, and we do not care about how it is transmitted, this belongs to other layers of the network.

For example, if you want to write an email to a friend from afar, we will take the lead in writing a letter, packaging a letter, and writing a letter at the application layer; when we put the mail into the mail box, the port of the mail box is the socket, after entering the socket, It is the transmission layer, network layer, etc. (Post Office, highway traffic management, or route) other levels of work. We never care about how the mail is sent from Xi'an to Beijing. We only know that it is okay to write the mail box. You can use the following two images to represent it:

Note that in the figure above, the two hosts are equivalent, but as agreed,We call one party initiating a request a client and the other end a server.It can be seen that the dialogue between two programs is completed through the socket portal. In fact, the most important information contained in the socket is the two information: local port information (local address and port number) and remote port information (remote address and port number ). Note the subtle changes in the above words. One is the local address and the other is the remote address.

Here is another term.Port. Generally, many applications run on our computers. They may all need to deal with remote hosts, therefore, the remote host requires an ID to identify which application on the local machine it wants to deal with. The ID here is the port. When a port is assigned to an application, the data from this port is always targeted at this application. There is a good example: you can think of the host address as a phone number, and think of the port number as an extension number.

In. NET, although we can directly program the socket. NET provides two classes to encapsulate socket programming, so that we can use it more conveniently. These two classes are TcpClient and TcpListener, and their relationships with sockets are as follows:

The figure above shows that TcpClient and TcpListener encapsulate sockets. We can also see that,TcpListener is used to receive connection requests, while TcpClient is used to receive and send Stream Data. This figure indicates that TcpListener keeps listening to the port continuously. Once a connection request is received, a TcpClient object can be obtained, tcpClient is used to send and receive data. At this time, TcpListener does not stop working, and it keeps listening to the port.

We consider the following situation: two hosts, host A and host B, who did not know where they were at first,When they want to perform a conversation, they always need one party to initiate a connection, while the other party needs to listen on a port of the local machine. When a listener receives a connection request and establishes a connection, it does not need to listen again when it sends and receives data between the listeners. Because the connection is full-duplex, it can use existing connections to send and receive data.We have previously defined that one party that initiates a connection is called the client and the other is called the server. Now we can conclude that:The server is always using the TcpListener class because it needs to establish an initial connection..

2. Three network chat program modes

Implementing an online chat program is supposed to be the content of the last article and the final program of this series. However, I think more encoding will be followed, and there should not be too much content, so I 'd like to put all the content here.

When this mode is used, it is called the full point-to-point mode. At this time, each computer is also a server because it needs to listen on the port. The difficulty in implementing this mode is: how do hosts (or terminals) Know the existence of other hosts? Generally, when a host goes online, it uses UDP for a Broadcast (Broadcast). In this way, it "notifies" other hosts that they are online and describe their locations, when the host receiving the broadcast sends back a response, the host will know the existence of other hosts. I personally don't like this method, but I used this mode in the Article C # compiling a simple chat program. Unfortunately, I didn't implement broadcast, so it is still not perfect.

The second method better solves the above problem. It introduces the server, which is used for broadcasting. The server keeps listening to the port. When a host goes online, it first connects to the server. After receiving the connection, the server places the host (address and port number) send to another online host (marked by a green arrow ). In this way, other hosts will know that the host is online and where it is located for connection and conversation. After the server is broadcast, because each host already knows the location of another host, the dialog between hosts is no longer expressed by the server (indicated by the Black Arrow), but directly connected. Therefore, when using this mode, each host still needs to listen on the port. When a host is offline, it is similar to the logon mode. The server receives a notification and sends it to other hosts.

The third mode is the simplest and most practical one. The login and offline modes of the host are the same as those of the second mode. Note that each host is first connected to the server when it goes online. Then, you can use this path to send messages from host A to host B, host A --> server --> host B. In this way, each host does not need to listen on the port, but only needs to listen on the server, which greatly simplifies development.

For some large files, such as images or files, if you want to send A file from host A to host B, the transmission efficiency through the server will be relatively low, in this case, you can set up A temporary connection between host A and host B to transfer large files. Close the connection after the file transfer ends (marked by an orange arrow ).

In addition, because all messages pass through the server, the server can also cache conversations between hosts, that is, when host A is sent to host B, if host B is offline, the server can cache messages. When host B connects to the server next time, the server automatically sends the cached messages to host B.

This is the final mode used in this series of articles, but it does not implement too many complex functions. Next, our theoretical knowledge has come to an end, starting the next stage-a long coding process.

Basic operation 1. The server listens to the port

Next, we will write some actual code. The first step is to enable listening for a port on the local machine. First, create a console application named "ServerConsole", which represents our server. If you want to communicate with the outside world, the first thing to do is to enable listening to the port, which is like opening a "Door" for the computer, all

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.