API:
-
socket:
套接字函数创建绑定到特定传输服务提供程序的套接字。
- 函数原型:
SOCKET WSAAPI socket([in] int af,[in] int type,[in] int protocol );
- 参数:
-
af:地址规范系列:
AF_INET:IPv4,AF_INET6:IPv6
-
type:新套接字的类型规范
SOCK_STREAM:TCP
SOCK_DGRAM:UDP
-
protocol:
如果指定值 0,则调用方不希望指定协议,服务提供商将选择要使用的 协议
-
- 返回值:如果未发生错误,套接字将返回引用新套接字的描述符,否则,将返回值INVALID_SOCKET,并且可以通过调用WSAGetLastError来检索特定的错误代码
- 函数原型:
-
listen:
侦听函数将套接字置于侦听传入连接的状态
-
函数原型:
int WSAAPI listen([in] SOCKET s,[in] int backlog );
-
参数:
s:表示绑定的未连接的套接字的描述符
backlog:挂起的连接队列的最大长度
-
返回值:如果未发生错误,侦听将返回0
-
-
accept:
连接套接字
-
sockopt:
设置套接字选项
- 函数原型:
int setsockopt([in] SOCKET s,[in] int level,[in] int optname,[in] const char *optval,[in] int optlen );
- 参数:
- s:标识套接字的描述符
- level:定义选项的级别
- optname:要为其设置的套接字选项
- optval:指向指定请求选项值得缓冲区的指针
- optlen:缓冲区大小
- 返回值:
- 函数原型:
TCP服务端:
#include <iostream>
#include <winsock.h>
#pragma comment(lib,"ws2_32.lib")int main() {WORD wVersionRequested = MAKEWORD(2, 2);WSADATA lpWSAData;//启动Winsock DLL的使用if (WSAStartup(wVersionRequested, &lpWSAData)) {std::cout << "WSAStartup Error!" << std::endl;system("pause");return 0;}if (LOBYTE(wVersionRequested)!=2||HIBYTE(wVersionRequested)!=2){WSACleanup();std::cout << "wVersion Error!" << std::endl;}//创建套接字:SOCKET socSrv = socket(AF_INET, SOCK_STREAM, 0);SOCKADDR_IN addSrv;addSrv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);addSrv.sin_family = AF_INET;addSrv.sin_port = htons(8000);//绑定:bind(socSrv, (sockaddr*)&addSrv, sizeof(sockaddr));//监听:listen(socSrv,5);SOCKADDR_IN addrClient;int nLength = sizeof(sockaddr);while (true) {//在套接字上尝试传入连接SOCKET sockConn = accept(socSrv, (sockaddr*)&addrClient, &nLength);//向客户端发送消息:send(sockConn, "已登录至服务器", strlen("已登录至服务器") + 1, 0);char recvBuffer[MAX_PATH]{ 0 };recv(sockConn, recvBuffer, MAX_PATH, 0);std::cout << "客户端消息:" << recvBuffer << std::endl;}closesocket(socSrv);WSACleanup();system("pause");return 0;
}
TCP客户端:
#include <iostream>
#include <winsock.h>
#pragma comment(lib,"ws2_32.lib")int main() {//初始化Winsock DLL的使用WORD wVersionRequested = MAKEWORD(2, 2);WSAData lpWSAData;if (WSAStartup(wVersionRequested, &lpWSAData)) {printf("WSAStartup Error!\r\n");system("pause");return 0;}if (LOBYTE(wVersionRequested) != 2 || LOBYTE(wVersionRequested) != 2) {printf("wVersion Error!\r\n");system("pause");return 0;}//创建套接字:SOCKET SocClient = socket(AF_INET, SOCK_STREAM, 0);SOCKADDR_IN addSrv;addSrv.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");addSrv.sin_family = AF_INET;addSrv.sin_port = htons(8000);//连接connect(SocClient, (sockaddr*)&addSrv, sizeof(sockaddr));char recvBuffer[MAX_PATH]{ 0 };recv(SocClient, recvBuffer, MAX_PATH, 0);printf("服务器端消息:%s\r\n", recvBuffer);send(SocClient, "Hello Server", strlen("Hello Server") + 1, 0);closesocket(SocClient);WSACleanup();system("pause");return 0;
}