TCP/IP-based c ++ network programming (API function Edition)

Source: Internet
Author: User

Source code: http://download.csdn.net/detail/nuptboyzhb/4169959

Network Programming Based on TCP/IP protocol

Define variable -- get Winsock version -- load Winsock database -- initialize -- create socket
-- Set socket options -- close socket -- uninstall Winsock database -- release all resources

The entire program architecture is divided into two parts: the Server Client.

Server socket program process:

Socket () → BIND () → listen → accept () → Recv ()/send () → closesocket ()

Client:

Socket → BIND () → connect () → send ()/Recv () → closesocket ()

 

Programming example:

The format of the message to be sent is as follows:

Typedef struct

{

Int ID;

Char data [255];

} Tcpmessage;

The application header file is as follows:

# Include <winsock2.h>

# Pragma comment (Lib, "ws2_32 ")

# Include <stdio. h>

Port: 4500

Server:

1. Initialization:

Wsadata;

Word sockversion = makeword (2, 2 );

If (wsastartup (sockversion, & wsadata )! = 0)

Return 0;

2. Create a socket:


Socket slisten = socket (af_inet, sock_stream, ipproto_tcp );

If (slisten = invalid_socket)

{

Printf ("socket error \ n ");

Return 0;

}

3. Bind the socket to the local address

// Load the address information in the sockaddr_in Structure

Sockaddr_in sin;

Sin. sin_family = af_inet;

Sin. sin_port = htons (4500); // The htons function converts the unsigned short integer number of the host into a network

// Byte order

Sin. sin_addr.s_un.s_addr = inaddr_any;

If (BIND (slisten, (lpsockaddr) & sin, sizeof (SIN) = socket_error)

{

Printf ("BIND error \ n ");

Closesocket (slisten );

Return 0;

}

4. listening port

If (Listen (slisten, 5)= Socket_error)

{

Printf ("Listen error \ n ");

Closesocket (slisten );

Return 0;

}

5. Wait for the connection to be accepted (if there is no connection, keep waiting)

Socket sclient; // used to save the socket returned by accept

Sclient = accept (slisten, 0, 0 );/If the/accept function fails to be called, the connection continues.

If (sclient = invalid_socket)

{

Printf ("accept () error ");

}

6. Use the socket returned by the accept function in step 1 for sending and receiving communication.

6.1 receive: (if not, wait !)

TcpmessageRevdata; // Defines the struct variable for receiving messages

Int ret =Recv(Sclient,(Char *) & revdata, Sizeof (Revdata), 0 );

If (Ret> 0) // indicates that the byte is received.

{

Switch (revdata. ID) // different IDS can have different responses.

{

Case 1:

........

Case 2:

........

}

}

6.2 sending:

TcpmessageSenddata;

Memset ((Char *) & senddata, 0, sizeof (Senddata); // Initialization is 0

Senddata. ID = 1; // assign a value to the ID member variable

Strcpy (senddata. Data, "\ r \ n .. character information to be sent ");

If (Send (sclient, (char *) & senddata, sizeof (senddata), 0)= Socket_error)

{

Char error [10];

Int errorcode = wsagetlasterror ();

ITOA (errorcode, error, 10 );

MessageBox (null, error, "failed to send, error code:", mb_ OK );

Printf ("send error! ");

}

7. Disable

Closesocket (sclient); // socket generated by accept

Closesocket (slisten); // server socket

Wsacleanup ();

Client

1. Initialization

Wsadata;

Word sockversion = makeword (2, 2 );

If (wsastartup (sockversion, & wsadata )! = 0)

Return 0;

2. Create a socket

Socket sclient = socket (af_inet, sock_stream, ipproto_tcp );

If (sclient = invalid_socket)

{

Printf ("socket error \ n ");

Return 0;

}

3. Bind the socket to the local address

// Load the server address information in the sockaddr_in Structure

Sockaddr_in servaddr;

Servaddr. sin_family = af_inet;

Servaddr. sin_port = htons (4500); // The htons function converts the unsigned short integer number of the host to the network

// In byte order, port 4500 is the port to connect to the server

Servaddr. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1"); // server IP Address

4. Connect to the server

If (connect (sclient, (sockaddr *) & servaddr, sizeof (servaddr) = socket_error)

{

Printf ("Connect error \ n ");

Closesocket (sclient );

Return 0;

}

// Note: Open the server first; otherwise, the connection fails.

5. send and receive communications

Use the send and Recv functions, which are the same as those on the server.

6. Disable

Closesocket (sclient); // The client has only one connection socket

Wsacleanup ();

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.