TCP Application Programming

Source: Internet
Author: User

TCP is the short name of transmission Control Protocol, a connection-oriented Transport layer protocol in TCP/IP, providing full duplex and reliable service in the network.

The main features of the TCP protocol are:

1) is a connection-based protocol.

2) Ensure accurate data arrival.

3) Ensure that the order in which the data arrives is the same as the order in which the data is sent.

4) The transmitted data has no message boundaries.

TCP protocol Communication flow:

1. Server-side first create a server socket

2. The server socket listens on a port waiting for the client to request

3. Client-side creation of client sockets

4. Client sends connection request to server side

5. The server confirms the connection to the client

6. Client and server-side use of established connections for communication

7. After the communication is complete, the client and the server shut down their respective connections

The process by which the server and client communicate using the Socket (shown)

The communication process between the server and the client

Socket Programming Basics:

Socket (network sockets) is the basic component of network communication, it can be named and addressed communication port, in use, each socket has a corresponding type and a related process. The following sections describe how to use sockets to build server-side programs and client programs.

The use of sockets to establish a TCP server-side program, generally requires the following several steps.

1) Create a server socket and bind it to the server's IP address and port number

int port = 888;

IPAddress ipadd=ipaddress.parse ("192.168.1.100");

TcpListener listener=new TcpListener (Ipadd, Port);

Note that you need to introduce a namespace:

Using System.Net;

Using System.Net.Sockets;

2) Listen to the server port and wait for the client connection request

Listener. Start ();

3) Confirm the connection to the client and create the socket object corresponding to the client

Socket clientsocket= Listener. AcceptSocket ();

4) data transfer via the established socket object and the connected client

A. Sending A message to the client

String msg= "everybody good";

byte [] outbytes=encoding.default.getbytes (MSG. ToCharArray ());

Clientsocket.send (outbytes);

B. Receiving data sent from the client

byte [] buff=new byte[1024];

Clientsocket.receive (Buff);

String msg = Encoding.Default.GetString (buff);

5) disconnecting from the client

Clientsocket.close ();

6) Close the server socket

Listener. Close ();

Using sockets to establish a TCP client program typically requires the following steps.

1) Create a client socket

TcpClient tcpclient=new TcpClient ();

Note that you need to introduce a namespace:

Using System.Net;

Using System.Net.Sockets;

2) Send a connection request to the remote server

int port = 888;

IPAddress ipadd=ipaddress.parse ("192.168.1.100");

Tcpclient.connect (Ipadd, Port);

3) Get the flow channel that communicates with the server

NetworkStream stream = Tcpclient.getstream ();

4) data transmission through the flow channel and the server side

A.. Send data to server side

String cmd= "chat|" + Useralias + ": Hello, everyone|";

byte [] outbytes=encoding.default.getbytes (cmd. ToCharArray ());

Stream.Write (outbytes,0,outbytes.length);

B Receive data sent from the server side

byte [] buff=new byte[1024];

int len= stream. Read (Buff,0,buff. Length);

String msg = Encoding.Default.GetString (Buff,0,len);

5) Disconnect from the server

Tcpclient.close ();

Application example of TCP programming--Network Instant messaging program

Function:

Log in, show online users, display user information for chat, group chat (send information to all online users will receive), private chat (chat with selected users, Send message only selected users can receive)

Design scheme:

1. Server-side design

Server-side Management chat tasks, and maintain a list of online users, forwarding users to send information, we designed the following features:

1) Listen to the specified port in the native IP address

2) When a client makes a request to the port, the server program immediately establishes a connection to the client and starts a new thread to process all requests from that client

3) perform the corresponding operation according to the different request commands sent by the client, and return the processing result to the client. The server can receive 4 message commands: CONN (make a new connection), chat (chat), PRIV (private chat), and exit (left), each message command can contain one or more message parameters, with the pipe symbol "|" To separate the parts of the message. Table 1 lists all the message commands.

Command format

Description

conn| user Name of sender |

This command is automatically sent by the client after the client has established a connection to the server side

After the server receives the command, add the user name to the online users list and send a command to update the online user list to all online users

Chat| Sender's user name: send content |

This command is automatically sent by the client program after the user enters the chat content on the client and clicks the Send button

After the server receives the command, the "sender's user name: Send content" is forwarded to all online users

priv| Sender's Username | Recipient's username | send Content |

This command is automatically sent by the client program when the user selects an online user on the client and selects the "Whisper" check box, enters the chat and clicks the Send button

After the server receives the command, the "sender's user name | Recipient's username | send Content |" forwarded to the corresponding recipient

exit| user Name of sender |

This command is automatically sent by the client program when the user clicks the Leave button on the client

After the server receives the command, the sender's user name is removed from the online users list and the Update online user List command is sent to all online users

2. Client-side design

The client side contains the user login window and the main window of the chat, which allows the user to log on to the server, and can send messages to the server, while also receiving the returned message from the server, we have designed the following functions:

1) Send a connection request to the server

2) After receiving confirmation from the server, establish a connection with the server and get the Flow channel (NetworkStream) to communicate with the server.

3) data communication with the server through the circulation channel. Send the server The 4 command requests that the server can recognize while receiving the message commands sent back by the server. There are 3 types of commands that clients can recognize: JOIN (notify a new user to enter a chat room), list (update online user list), QUIT (Close client application), each message command can contain one or more message parameters, with the pipe break "|" To separate the parts of the message. Table 2 lists all the message commands.

command format

description

join| just logged in username |

The command is automatically sent to the client by the server side after receiving the Conn command on the server side to notify a new user to enter the chat room

list| username 1| user name 2| ... (All online user names) |

The command is sent to the client automatically by the server side after receiving a conn command from the client (with a new user entry) or the Exit command (with an online user exit). To notify all online users to update their online user list

After the client receives the command, refreshes the online user list in its own window

quit|

This command is sent to the client (the client sending the exit command) automatically by the server-side program after receiving the exit command from the client on the server side. To notify the client to close the connection and close the client segment program

The client (the client sending the Exit command) receives the command, closes the connection to the server and closes the client segment program

Note: The above commands are customized and can be added or changed as needed, as long as the client and server-side message command formats are guaranteed to be the same.

Solution:

1, server-side implementation

Create a new Windows Forms application named Chatserver, in order to use the IPAddress object, the socket object, and the thread object, introduce the namespace System.Net, System.Net.Sockets and System.Threading.

Using multi-threading on the server side, each user connects with a separate thread, and when the server starts running, a thread is started waiting for the client to connect (implemented in method Startlisten ()). When a request is received, the server immediately launches a new thread to process the information interaction with the client (implemented in method StartService ()). A client class is defined here to hold the user name of each online user and the socket object connected to the server, and when the socket connection is established, it is stored in a client object immediately so that each user has his or her own socket, which can later be used for different users ' The Socket object is manipulated to interact with the client's data.

Cheung See code ChatServer.cs.

2, the implementation of the client

Create a new Windows Forms application named Chatserver, in order to use the IPAddress object, the socket object, and the thread object, introduce the namespace System.Net, System.Net.Sockets and System.Threading.

On the client, first create the client socket and connect to the server to specify the port, while obtaining the traffic channel to communicate with the server, after the user logs in, send the CONN command to the server to indicate that a new user enters the chat room, the server will return all the online user's nickname, select a different person, and select the "Whisper" check box, Then you can have a private chat.

TCP Application Programming

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.