The socket communication process and examples based on TCP

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Socket is also called the socket, used to realize network communication, by calling the system of API, and the machine can transfer data remote. Socket has many kinds of protocols, and this article mainly discusses the TCP part of the content, that is to say back to say mainly refers to TCP Socket.

The general process of calling Socket:

The server: socket(), bind(), listen(), accept(), send(), recv(), close()

The client: socket(), connect(), send(), recv(), close()

Blocking socket (synchronous socket)

The process or thread execution to some socket function must wait for the socket event, if the event does not occur, the socket function does not return immediately, process or thread is blocked.

Features: simple, suitable for answering occasions one on one, rarely used in server, or with multiple threads use

Function Returns value explain The blocking situation
accept() Returns the connection to socket handle new. Buffer queue without new waiting for the connection
connect() Returns the -1 that the connection fails, the other normal. Connection blocking.
recv() Returns value less than 1 representative reception failure, other representatives receiving data length. Send buffer data waiting to send, receive buffer blocking or no data.
send() Returns the -1 representing the transmission failure, the other to send the data length Blocking send buffer is not enough space to store the data is sent

Non blocking socket (asynchronous socket)

Don't have to wait for the socket event process or thread executes the socket function, once implemented immediately returns. According to the different value can be executed judgment function, if the event occurs and blocking the same way, if the event does not occur returns a code to inform the event did not occur, and the process or thread can not be blocked, continue to implement.

Features: the function returns immediately, without blocking the process, performance than the blocking high, suitable for directly call the main thread, the main thread will not cause o

Because socket is blocked by default, so to set up a non blocking mode:


#ifdef WIN32 
	DWORD nMode = 1; 
	ioctlsocket(m_sock, FIONBIO, &nMode);
#else
	int r = fcntl(fd, F_GETFL, 0));
	fcntl(fd, F_SETFL, r|O_NONBLOCK);
#endif
The difference between TCP and UDP


Protocol specification Socket create
TCP Transmission control protocol, reliable connectivity. The first establishing a connection and data transmission. Provide the timeout retransmission, data validation, flow control mechanism, ensure the data transmission without error. socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
UDP User datagram protocol, connection service is not reliable. No connection can send data, there is no timeout retransmission mechanism, the transmission speed is very quick. socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)

The Socket example

Following a simple example to illustrate the interaction between server and client

The server server.cpp


#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

#define PORT 8080

int main()
{
	//Initialize the Winsock service
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);

	//Create socket
	SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	struct sockaddr_in svraddr;
	svraddr.sin_family = AF_INET;
	svraddr.sin_port = htons(PORT);
	svraddr.sin_addr.s_addr = htonl(INADDR_ANY);

	//Binding of socket
	bind(sock, (struct sockaddr*)&svraddr, sizeof(svraddr));

	//Monitor socket
	listen(sock, 5);

	while(1)
	{
		struct sockaddr_in addr;
		int len = sizeof(SOCKADDR);

		char buf[1024] = {0};

		//Accept client connections
		SOCKET client = accept(sock, (struct sockaddr*)&addr, &len);

		char* ip = inet_ntoa(addr.sin_addr);
		printf("accept client: %s\r\n", ip);

		//The receiving client data
		if(recv(client, buf, 1024, 0) >0)
		{
			printf("recv client: %s\r\n", buf);

			//To transmit data to the client
			send(client, "hello, client", strlen("hello, client"), 0);
		}
		closesocket(client);
	}

	//Close socket
	closesocket(sock);

	//Close the Winsock service
	WSACleanup();

	return 0;
}
The client client.cpp

#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")

#define REMOTE_IP "127.0.0.1"
#define REMOTE_PORT 8080

int main()
{
	//Initialize the Winsock service
	WSADATA wsaData;
	WSAStartup(MAKEWORD(2,2), &wsaData);

	//Create socket
	SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

	struct sockaddr_in svraddr;
	svraddr.sin_family = AF_INET;
	svraddr.sin_port = htons(REMOTE_PORT);
	svraddr.sin_addr.s_addr = inet_addr(REMOTE_IP);

	//Connecting the socket
	if( connect(sock, (struct sockaddr*)&svraddr, sizeof(svraddr)) != -1)
	{
		//To send data to the server
		if(send(sock, "hello, server", strlen("hello, server"), 0) != -1)
		{
			//The receiving server data
			char buf[1024] = {0};
			if(recv(sock, buf, 1024, 0) >0)
			{
				printf("recv server: %s\r\n", buf);
			}
			
		}
	}
	else
	{
		printf("can not connect server\r\n");
	}

	//Close socket
	closesocket(sock);

	//Close the Winsock service
	WSACleanup();
	getchar();
	return 0;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Terence at December 12, 2013 - 11:32 AM