Description: The main sub-step example is given a TCP socket programming Windows platform; network programming using the WINDOWS Winsock network communication to specifications; for details of each portion will be described procedure.
There are three types of transfer socket SOCK_STREAM SOCK_DGRAM SOCK_RAW;
See in particular: https://blog.csdn.net/bjyddxhfxq/article/details/51119653
Source full version download: https://download.csdn.net/download/ckzhb/10601058
Article Directory
- First, the server
- 1, load the socket library, creating the socket.
- 2, bind the socket to an IP address and a port
- 3, listening on the specified port
- 4, waiting for a client request, if the request is received, the establishment of a connection to the corresponding socket
- 5, the client receives the data
- 6, transmits data to the client
- 7, the socket is closed, close-loaded socket library
- Second, the client
- 1, load the socket library, create socket
- 2, issues a connection request to the server
- 3, for data transmission between the server and
- 4, the socket is closed, close-loaded socket library
- Third, the operating results
First, the server
Function: monitoring port, waiting for a client request; successful connection is established, the server every time the input data, transmitting a group of data; if the input q, stops sending.
1, load the socket library, creating the socket.
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib") //静态加入一个lib文件
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(sockVersion, &wsaData) != 0) //WSAStartup返回0表示设置初始化成功
return 0;
/*创建套接字*/
//AF_INET表示IPv4,SOCK_STREAM数据传输方式,IPPROTO_TCP传输协议;
SOCKET listenSocket = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if (listenSocket == INVALID_SOCKET)
{
printf("套接字创建失败");
WSACleanup();
return 0;
}
Description:
- Microsoft WORD SDK 16-bit unsigned integers; WSADATA is a structure;
- MAKEWORD (a, b) is a macro that is used to specify where the Winsock version;
- WSAStartup, namely WSA (Windows Sockets Asynchronous, Windows asynchronous socket) start command; WSAStartup must be the first application or a Windows Sockets DLL function call. It allows an application or DLL version numbers indicate the Windows Sockets API and get the details of a particular Windows Sockets implementation. Application or DLL can only be successful WSAStartup before calling for further Windows Sockets API function after () call.
- Function socket (), socket () function is used to assign a socket descriptor and the resources used in the specified address family, type and protocol data; If no error occurs, Socket () returns a reference to describe the new socket word. Otherwise, return INVALID_SOCKET error.
2, bind the socket to an IP address and a port
/*绑定IP和端口*/
//配置监听地址和端口
sockaddr_in addrListen;
addrListen.sin_family = AF_INET; //指定IP格式
addrListen.sin_port = htons(8888); //绑定端口号
addrListen.sin_addr.S_un.S_addr = INADDR_ANY; //表示任何IP service.sin_addr.s_addr = inet_addr("127.0.0.1");
if (bind(listenSocket, (SOCKADDR*)&addrListen, sizeof(addrListen)) == SOCKET_ERROR) //(SOCKADDR*)
{
printf("绑定失败");
closesocket(listenSocket);
return 0;
}
Description:
- sockaddr_in is a data structure; parameter do bind, connect, recvfrom, sendto other functions, information indicating the address.
- bind()函数int bind( int sockfd , const struct sockaddr * my_addr, socklen_t addrlen);
bind () function to assign an address by binding to create a socket interface.
3, listening on the specified port
/*开始监听*/
if (listen(listenSocket, 5) == SOCKET_ERROR)
{
printf("监听出错");
closesocket(listenSocket);
return 0;
}
Description:
- int listen( int sockfd, int backlog);
- sockfd: identifies a bundled socket descriptor is not connected.
- backlog: wait a maximum length of the connection queue.
4, waiting for a client request, if the request is received, the establishment of a connection to the corresponding socket
/*等待连接,连接后建立一个新的套接字*/
SOCKET revSocket; //对应此时所建立连接的套接字的句柄
sockaddr_in remoteAddr; //接收连接到服务器上的地址信息
int remoteAddrLen = sizeof(remoteAddr);
printf("等待连接...\n");
/*等待客户端请求,服务器接收请求*/
revSocket = accept(listenSocket, (SOCKADDR*)&remoteAddr, &remoteAddrLen); //等待客户端接入,直到有客户端连接上来为止
if (revSocket == INVALID_SOCKET)
{
printf("客户端发出请求,服务器接收请求失败:\n",WSAGetLastError());
closesocket(listenSocket);
WSACleanup();
return 0;
}
else
{
printf("客服端与服务器建立连接成功:%s \n", inet_ntoa(remoteAddr.sin_addr));
}
Description:
- First, define a new socket, note that the socket is different from the previous, data transmission, use the socket.
- SOCKET accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen);
A function to extract the connector from the first connector wait queue, creating a new kind of socket and returns a handle;
- sockfd: socket descriptor, the listening socket connector (rear) in the listen;
- addr :( optional) pointer to a buffer, wherein the receiving entity is the address of the connected communication layer art. The actual format of the parameter is determined by the Addr address family socket is created produced.
- addrlen :( optional) pointer, input parameters, used together with addr, point address addr integer length there.
5, the client receives the data
char revData[255] = "";
char *sendData = new char[100];
/*通过建立的连接进行通信*/
int res = recv(revSocket, revData, 255, 0);
if (res > 0)
{
printf("Bytes received: %d\n", res);
printf("客户端发送的数据: %s\n", revData);
}
else if (res == 0)
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
Description:
int recv( SOCKET s, char FAR *buf, int len, int flags );
Whether the client or server application receives data from the other end of the TCP connection recv function, the return value is determined according to the receiving condition data.
- s: Specifies the receiving end socket descriptor;
- buf: indicates a buffer that is used to store data received recv function;
- len: specified length of buf;
- flag: s is typically 0;
6, transmits data to the client
while (cin>>sendData)
{
//cout << strlen(sendData) << endl;
if (strcmp(sendData, "q") == 0)
{
printf("服务器停止发送数据!\n");
break;
}
//发送数据
send(revSocket, sendData, strlen(sendData), 0);
}
Description:
int send( SOCKET s, const char FAR *buf, int len, int flags );
Meaning basically the same recv () function.
7, the socket is closed, close-loaded socket library
closesocket(listenSocket);
WSACleanup();
Second, the client
Function is the same as part of the server, not listed separately!
1, load the socket library, create socket
WORD sockVerson = MAKEWORD(2, 2);
WSADATA wsaData;
if (WSAStartup(sockVerson, &wsaData) != 0)
return 0;
//建立客户端socket
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET)
{
printf("套接字创建失败");
WSACleanup();
return 0;
}
2, issues a connection request to the server
//定义要连接的服务器地址
sockaddr_in addrConServer;
addrConServer.sin_family = AF_INET;
addrConServer.sin_port = htons(8888);
addrConServer.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
if (connect(clientSocket, (SOCKADDR*)&addrConServer, sizeof(addrConServer)) == SOCKET_ERROR)
{
printf("客户端建立连接失败!\n");
closesocket(clientSocket);
WSACleanup();
return 0;
}
else
printf("客户端建立连接成功,准备发送数据!\n");
Description:
int connect(SOCKET s, const struct sockaddr * name, int namelen);
This function creates the specified external port connections for flow type socket (SOCK_STREAM type), the use of the name to establish a connection with a remote host, once a successful return call to the socket, it can receive or transmit data. For datagram socket type (SOCK_DGRAM type) is set to a default destination address and use it for subsequent send () and the recv () call.
3, for data transmission between the server and
//发送数据
int sendRes = send(clientSocket, sendBuf, (int)strlen(sendBuf), 0);
if (sendRes == SOCKET_ERROR)
{
printf("客户端send()出现错误 : %d\n", WSAGetLastError());
closesocket(clientSocket);
WSACleanup();
return 0;
}
else
printf("客户端发送数据成功!\n");
//接收服务端数据
/*通过建立的连接进行通信*/
do
{
char revSerData[100] = "";
res = recv(clientSocket, revSerData, sizeof(revSerData), 0);
if (res > 0)
{
printf("Bytes received: %d\n", res);
printf("服务器发送的数据: %s\n", revSerData);
}
else if (res == 0)
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while (res > 0);
4, the socket is closed, close-loaded socket library
closesocket(clientSocket);
WSACleanup();
Third, the operating results
First run the server, run the client;
Then the input data transmitted in the intended server;