Network Programming Instant messaging Program (chat room)------(i) Brief introduction of communication process and communication protocol custom _ programming

Source: Internet
Author: User
Tags array length format message server port

Before I begin, I'd like to describe what this so-called communication program is all about. The communication program is similar to a weak version of QQ, login needs to register, after successful login, you can achieve instant communication, group chat, private chat, but also can be transmitted documents. Let's get to the last picture

Server side: Client Login: Client main interface:

The so-called real-time communication program, that is, the use of TCP and UDP transmission protocol, information, file transmission. So what is TCP and what is UDP?

     TCP is the abbreviation of Transmission Control PROTOCOL (Transmission Control Protocol), which is a connection-oriented transport layer protocol in the TCP/IP system, providing Full-duplex and reliable service in the network. The main features of TCP protocol are: based on the connection protocol, the data transmission is more stable, and can guarantee the punctual and timely.                                                                                                            

UDP, the abbreviation of user Datagram Protocol (Subscriber Datagram Protocol), is a connectionless transport layer protocol in the OSI Reference Model, which provides a simple and unreliable information delivery service for transaction-oriented. The main features of the UDP protocol are: Based on connectionless protocol, data transmission quickly, quick response, while the shortcomings are also very obvious, that is, the data transmission is not stable, can not guarantee the order of arrival, there may be a lack of data.

We are familiar with the QQ is a TCP and UDP two kinds of protocols combined with a real-time communication program, in our session, chat, the use of UDP protocol, through the server transit mode. As we all know, UDP protocol is unreliable, it just send, regardless of whether the other party received, but its transmission is very efficient. However, as a chat software, how can you use such an unreliable way to transmit messages. Thus, Tencent adopted the upper layer protocol to ensure reliable transmission: if the client sends a message using the UDP protocol, the server receives the packet and needs to send back an answer packet using the UDP protocol. This ensures that messages can be transmitted without omission. It occurs when the client sees "message sending failed" but the other person receives the message because the client-issued message server has received and forwarded successfully, but the client did not receive the server's answer packet due to the network reason. We use TCP based data Transfer protocol when we file transfer, because we need to ensure the order of data transmission arrives, and we must ensure that there is no loss of data.

In our. NET platform if you want to achieve real-time communication requires the help of the socket network programming, socket (network sockets) is the basic component of network communication, it can be named and addressed the communication port, in use, each Socket has a corresponding type and a related process. Before we begin to introduce the socket to create instant messaging, we need to understand the operation process of using TCP for Instant Messaging:

Below I will combine this flowchart, step-by-step with you talk about the specific process of communication.

1, the creation of service-side sockets, listening to the local IP and a specific port, the machine as a service side. (The following is just a simple demo example)

int  port = 11615;//Listening port, preferably set larger, avoid and some specific port conflicts IPAddress Ipadd=ipaddress.parse ("192.168.245.1"); We passed the Dns.getbyhostname (). Arrylist[], the dynamic acquisition of native IP, here is only an example. TcpListener listener=new TcpListener (Ipadd, port);//Create Listener Object

2, listening to the server port, waiting for client connection request

Listener. Start ();

3. Create a socket for the client and send a connection request to the remote server

TcpClient tcpclient=new tcpclient (); int  port = 11615;ipaddress ipadd=ipaddress.parse ("192.168.245.1");        Tcpclient.connect (Ipadd, Port);

4, the service side confirms the connection with the client, and creates the socket object corresponding to the client

Socket clientsocket= Listener. AcceptSocket ();

5, the client to obtain communication with the server flow channel

NetworkStream stream = Tcpclient.getstream ();

6, the client through the flow channel and server-side data transmission

6.1, the client sends the number to the server side

String  

6.2, the client received data from the server side sent

byte [] buffer=new byte[1024];int length= stream. Read (Buff,0,buff. Length); string msg = Encoding.Default.GetString (buffer,0,length);

7, the service side accepts the client request

7.1, the server to send data to the client

String  hello= "Hello World." "; Byte [] buffer=encoding.default.getbytes (hello); stream. Write (Buffer,0,buffer. Length);

7.2, the server to receive data from the client side sent

byte [] buffer=new byte[1024];int length= stream. Read (Buff,0,buff. Length); string msg = Encoding.Default.GetString (buffer,0,length);

8, the service side disconnect from the client

Clientsocket.close ();

9, the client disconnected from the service side of the connection

Tcpclient.close ();

10, service-side shutdown service socket

Tcpclient.close ();

The general communication process is like this, however, there is a difference in the actual application, because we want to involve the interaction between multiple clients, and the server is just the equivalent of an intermediary medium, receiving the message sent by the client and forwarding the message to another client, if there are multiple clients, and communication, And this time need to use multithreading for communication management and control.

The specific process is as follows:

First, we need to create a Tcplister object on the server side, enabling a thread that is dedicated to listening to the client's request.

Second, whenever a client makes a request, the Tcplister object immediately creates a socket that is dedicated to communication and a client-requested socket.

Enabling a new thread at the same time is dedicated to communicating with the client.

On the client side, we only need to create a TcpClient object, and enable a new thread to be dedicated to the acceptance of the information.

In the specific process, we also need to customize some of the column of the message Communication protocol, in the message internal use "|" The pipe character splits its contents, and by parsing the protocol we can handle different messages differently. In this application procedure, the specific communication protocol is as follows:

The receive protocol on the server side is as follows:

Command format

The first byte in a byte array that receives the traffic sent by the client msg[0]

Description

1, if msg[0] then the file is sent, then traverse the online list of users, like users online users send the byte array

2, if msg[0]!=0, then the message sent over the string, the direct encoding byte array into a string, and the following analysis of the string, according to different analysis results to execute different commands.

on| Sender's Username |

1. The command is automatically sent by the client after the client establishes a connection with the server side

2, the server side received the command, the "user name" added to the online user list and send messages to all online users "* * * online. "

Off| Sender's Username |

1, the command is in the user online, or away from the execution, to send to the client list of online personnel, the client received the information will be updated online list.

Msg| Recipient Name | sender name | send Content |

msgall| Sender's Username | send Content |

1, this command is the user clicks the Send Message button, sends the information, if the user must select to send the object

2, the server received the message, the message to resolve, obtain the recipient user name, and from the online list to obtain the corresponding communication socket, the "sender user name said" send Content "in this format message sent back to the client

3, if it is msgall, then the mass message, server-side received the command, will traverse the online user list of users, and one by one to the online users send "sender's username said ' send content '" Such information sent to all online users

The client receives the protocol as follows:

Command format

Description

Accept the first byte in the stream byte array sent by the server msg[0]

If msg[0]==0 indicates that the server sent the file, the direct new file stream starts reading from the second byte in the received byte array, reading length minus one byte of the byte array length, and saving the file locally.

If msg[0]!=0 indicates that the server sends a message string and then parses it according to the following command format, and then makes a different action

online| user name just logged in |

After the client received the command, in the chat string to see "* * *" on-line notice.

off| User 1, User 2, user 3, |

This command receives the off and on command from the client on the server side, sends back the command to the client, and then the client resolves the command to update the online personnel list.

These are the communication formats for this instant messaging program, in the next section, I will take you step-by-step to build the service side of the Instant messaging program, in the process of construction will gradually show you the application of Tcplister, as well as related to the multithreaded knowledge involved.

       Well, this section is here, I hope to bring a little help, but also hope that everyone a lot of guidance.                                                                                                                      

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.