TCP-based socket programming __ Programming

Source: Internet
Author: User
Tags connect socket function prototype set socket server port htons

Based on TCP (connection-oriented) socket programming, divided into client and server side.

The process for the client is as follows:

(1) Create socket (socket)

(2) Send a connection request to the server (connect)

(3) Communication with server side (SEND/RECV)

(4) Close socket

The server-side process is as follows:

(1) Create socket (socket)

(2) Bind the socket to a local address and port (BIND)

(3) Set socket to listener mode, prepare to receive client request (listen)

(4) Waiting for the arrival of the customer request, when the request arrives, accept the connection request, return a new socket corresponding to this connection (accept)

(5) Communication with the returned socket and client (SEND/RECV)

(6) Return and wait for another client request.

(7) Close the socket.

The following is a concrete example to explain the specific process and related functions.

Client code, running in VS2008

ClientTest.cpp: Defines the entry point for a console application. #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <winsock2.h> #define Server_por
	T 5208//Listening port int _tmain (int argc, _tchar* argv[]) {WORD wversionrequested;
	Wsadata Wsadata;
	int ret; SOCKET sclient; Connect socket struct sockaddr_in saserver;
	Server address information char *ptr;

	BOOL fsuccess = TRUE; Winsock Initialization wversionrequested = Makeword (2, 2);	The version of the Winsock DLL you want to use is ret = WSAStartup (wversionrequested, &wsadata);
		Load socket font if (ret!=0) {printf ("WSAStartup () failed!\n");
	return 0; }//Confirm Winsock DLL Support version 2.2 if (Lobyte (wsadata.wversion)!=2 | |
		Hibyte (wsadata.wversion)!=2) {wsacleanup ();//Release the resources allocated for the program, terminate the use of WinSock Dynamic library printf ("Invalid WinSock version!\n");
	return 0;
	//create socket, use TCP protocol sclient = socket (af_inet, sock_stream, ipproto_tcp);
		if (sclient = = Invalid_socket) {wsacleanup ();
		printf ("Socket () failed!\n");
	return 0; //Build server address information saserver.sin_family = af_inet; Address Family Saserver. Sin_port = htons (Server_port); Attention translates into network node sequence saserver.sin_addr. S_un.

	S_ADDR = inet_addr ("127.0.0.1");
	Connect server ret = Connect (sclient, (struct sockaddr *) &saserver, sizeof (Saserver));
		if (ret = = socket_error) {printf ("Connect () failed!\n"); Closesocket (sclient);
		Close socket WSACleanup ();
	return 0; 
	} char sendmessage[]= "Zhongxingpengyue";
	ret = Send (sclient, (char *) &sendmessage, sizeof (SendMessage), 0);
	if (ret = = socket_error) {printf ("Send () failed!\n");
	else printf ("Client info has been sent!");
	Char recvbuf[100];
	Recv (sclient,recvbuf,100,0);
	printf ("%s\n", recvbuf); Closesocket (sclient);
	Close socket WSACleanup ();
	GetChar ();
return 0;

 }

The first step is to load the socket. Use the WSAStartup function, such as: ret = WSAStartup (wversionrequested, &wsadata). The prototype of the WSAStartup function is

int WSAStartup (WORD wversionrequested, Lpwsadata lpwsadata)

The first parameter, wversionrequested, is used to specify the version of the Winsock library to be loaded. Use Makeword (X,Y) macros to assign values. X is a high byte that represents the minor version number, and Y is a low byte, representing the major version number. Makeword (2, 2) indicates that the version number is 2.2.

The second parameter is a pointer to the WSADATA structure, a return value that holds information about the library version.

The second step is to create a socket. Use the socket function, such as: Sclient = socket (af_inet, Sock_stream, ipproto_tcp). The prototype for the socket function is:

Socket socket (int AF, int type, int protocol);

The first parameter, specifies the address family, for the TCP/IP protocol socket, only for af_inet;

The second parameter specifies the socket type, sock_stream refers to generating a streaming socket, sock_dgram refers to generating a datagram socket, and the TCP/IP protocol uses SOCK_STREAM.

The third parameter, which is associated with a particular address family, is typically a ipproto_tcp TCP protocol. You can also write 0, the system automatically chooses an appropriate protocol based on the address format and socket category.

If the socket is created successfully, a socket descriptor for the new socket data type is returned, and if it fails, the Invalid_socket is returned, which allows you to determine whether the creation was successful.

The third step is to connect to the server. Use the Connect function, such as: ret = connect (sclient, (struct sockaddr *) &saserver, sizeof (Saserver)). The function prototype of connect function is

int Connect (SOCKET s, const struct SOCKADDR far* name, int namelen);

The first parameter is the descriptor for the socket that will be connected above, that is, the return value of the socket that was previously created sclient.

The second parameter is the address information for the server side to which you want to connect. It is a struct type struct sockaddr_in that requires building server address information before calling the Connect function. The definition of sockaddr_in is as follows:

struct sockaddr_in{short

sin_family;

unsigned short sin_port;

struct IN_ADDR sin_addr;

Char sin_zero[8]

};


When you set up a server port, you use the Htons function, which converts a u_short type of value from host byte order to TCP/IP network byte order, because different computers hold multiple bytes in different order (based on the Intel CPU is high byte stored in low address, low byte stored in high address), Therefore, when communication between different hosts in the network, the network byte order should be adopted uniformly. When you set up the server IP address, you use the INET_ADDR function, which converts the string of decimal-dotted IP addresses into a unsigned long type. The Inet_ntoa function does the opposite conversion.

The third parameter is the size of the server-side address structure.

Fourth step, send. Use the Send function to send data to the server, such as: ret = Send (sclient, char *) &sendmessage, sizeof (SendMessage), 0). The Send function is a prototype of

int send (SOCKET s, const char far* buf, int len, int flags);

The first argument is a socket that has already been connected to the server.

The second argument, pointing to a pointer to the buffer that contains the data to send.

The third argument is the length of the buffer to which you are pointing. Exactly, it should be the length of the data to be sent, because all data that is not a buffer is sent at the same time.

The fourth parameter, whose value will affect the behavior of the function, is generally set to 0.

If the send fails, send returns SOCKET_ERROR, which can be used to determine if the send was successful.

Fifth step, receive. Use the RECV function to receive data sent by the server, such as recv (sclient,recvbuf,100,0). The prototype of the RECV function is

int recv (SOCKET s, const char far* buf, int len, int flags);

The parameters of the RECV function have the same meaning as the Send function argument, except that the second parameter is a pointer to the buffer used to hold the received data. The return value of the RECV function should be the length of the received data, if the return socket_error indicates a receive failure, and a return of 0 indicates the server-side shutdown connection.

The sixth step is to close the socket and release the resource. Use the Closesocket function to close a socket, such as closesocket (sclient), and use the WSACleanup function to release resources allocated for the program, terminating the use of the Winsock dynamic library, such as WSACleanup ();

Server-side code, run in vs2008

ServerTest.cpp: Defines the entry point for a console application. #include "stdafx.h" #include <stdio.h> #include <winsock2.h> #define SERVER_PORT 5208//Listening port int _tmain (
    int argc, _tchar* argv[]) {WORD wversionrequested;
    Wsadata Wsadata;
    int ret, nleft, length; SOCKET Slisten, sserver; Listen socket, connect socket struct sockaddr_in saserver, saclient; The address information char *ptr;//the pointer that is used to traverse the information//winsock initialize Wversionrequested=makeword (2, 2);
    The version of the Winsock DLL you want to use Ret=wsastartup (wversionrequested, &wsadata);
        if (ret!=0) {printf ("WSAStartup () failed!\n");
    return 0;
    //create socket, use TCP protocol slisten=socket (Af_inet, Sock_stream, ipproto_tcp);
        if (Slisten = = Invalid_socket) {wsacleanup ();
        printf ("Socket () faild!\n");
    return 0; //build Local address information saserver.sin_family = af_inet; Address Family Saserver.sin_port = htons (Server_port); Note translates into a network byte order saserver.sin_addr. S_un. S_ADDR = htonl (Inaddr_any);
 Use Inaddr_any to indicate any address 
    binding ret = Bind (Slisten, (struct sockaddr *) &saserver, sizeof (Saserver)); if (ret = = socket_error) {printf ("bind () faild!
        Code:%d\n ", WSAGetLastError ()); Closesocket (Slisten);
        Close socket WSACleanup ();
    return 0;
    //Listen for connection requests ret = Listen (Slisten, 5); if (ret = = socket_error) {printf ("Listen () faild!
        Code:%d\n ", WSAGetLastError ()); Closesocket (Slisten);
    Close socket//return 0;
    printf ("Waiting for client connecting!\n");
    printf ("Tips:ctrl+c to quit!\n");
	Block waiting to accept client connection while (1)//Loop listener client, never stop, so, in this project, we don't have a heartbeat packet.
		{length = sizeof (saclient);
		Sserver = Accept (Slisten, (struct sockaddr *) &saclient, &length); if (sserver = = Invalid_socket) {printf ("Accept () faild!
			Code:%d\n ", WSAGetLastError ()); Closesocket (Slisten);
			Close socket WSACleanup ();
		return 0;  Char sendmessage[]= "Hello client"; Send Message to client send (Sserver,sendmessage,strlen (SendMessage)+1,0);
		Char receivemessage[5000];
		Nleft = sizeof (receivemessage);
		PTR = (char *) &receiveMessage;
			while (nleft>0) {//Receive data RET = recv (Sserver, PTR, 5000, 0);
				if (ret = = socket_error) {printf ("recv () failed!\n");
			return 0;
				} if (ret = 0)//client has closed connection {printf ("client has closed the connection\n");
			Break
			} nleft-= ret;
		PTR + ret;
		

	printf ("Receive message:%s\n", receivemessage);//Print the message we received.
  }//Closesocket (Slisten);
  Closesocket (sserver);
	WSACleanup ();
return 0;
 }


The first step is to load the socket font, and the client has to load the socket.

The second step is to create a listening socket, slisten=socket (af_inet, Sock_stream, ipproto_tcp), and still use the socket function.

The third step, binding. Using the BIND function, the function is to bind a created socket to a local address and port, and the function's prototype is:

int bind (SOCKET s, const struct SOCKADDR far* name, int namelen);

The first parameter, specifying the socket to bind;

The second parameter, specifying the address information for the socket, which is the address information for the server, is still a pointer to the structure of the struct sockaddr_in type. This structure is the same as when the client calls the Connect function to build the server address information. Where inaddr_any is to indicate any address, because the server contains a possible number of network cards, there may be multiple IP addresses, this point to select an arbitrary address.

The third parameter, the length of the information for the address.

Step fourth, listen for connections. Using the Listen function, this function sets the specified socket to listening mode, such as RET = Listen (Slisten, 5). Function prototype is

int Listen (SOCKET s, int backlog);


The first argument is the socket descriptor to be set to listen for.

The second argument is the maximum length of the queue to wait for the connection. Note that this value is set to set the maximum length of the queue to wait for the connection, rather than the maximum number that can be connected on one port. For example, set to 5, when 6 connection requests arrive at the same time, the first 5 connection requests are placed in the waiting request connection queue, and the server processes the request services sequentially, but the 6th connection request is rejected.

Step fifth, accept the client's connection request. Use the Accept function to accept connection requests sent by clients, such as Sserver = Accept (Slisten, struct sockaddr *) &saclient, &length);

Socket accept (socket s, struct sockaddr far* addr, int far* addrlen);


The first argument is a descriptor for a socket that has been set to listening mode.

The second parameter, which is a return value, points to a variable in a struct sockaddr type of struct that holds the IP address information and port information of the client initiating the connection.

The third parameter, also a return value, points to an integer variable that holds the length of the address information returned.

The Accept function return value is a descriptor for the socket type of a client-server connection that identifies the client on the server side.

The sixth to seventh step is to send and receive, respectively, using the Send and RECV functions, here and the same as the client, no longer repeat.

The Accept function is placed in a dead loop, listening to the client's request. When the server shuts down, all sockets are closed and resources are freed.

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.