TCP简单服务器端代码
#include <iostream>
#include <winsock2.h>
#include <stdio.h>
#pragma comment(lib,"ws2_32.lib")
int main()
{
//初始化WSA
WORD sockVersion = MAKEWORD(2, 2);
WSADATA wsaData;//WSADATA结构体变量的地址值
//int WSAStartup(WORD wVersionRequested, LPWSADATA lpWSAData);
//成功时会返回0,失败时返回非零的错误代码值
if (WSAStartup(sockVersion, &wsaData) != 0)
{
std::cout << "初始化网络库失败,错误码:" << WSAGetLastError() << std::endl;
return -1;
}
//创建套接字
SOCKET socketListen = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (socketListen == INVALID_SOCKET)
{
std::cout << "创建套接字失败,错误码:" << WSAGetLastError() << std::endl;
return -1;
}
//绑定IP和端口
sockaddr_in sin;//ipv4的指定方法是使用struct sockaddr_in类型的变量
sin.sin_family = AF_INET;
sin.sin_port = htons(8088);//设置端口。htons将主机的unsigned short int转换为网络字节顺序
sin.sin_addr.S_un.S_addr = inet_addr("192.168.11.149");//IP地址设置成INADDR_ANY,让系统自动获取本机的IP地址
//bind函数把一个地址族中的特定地址赋给scket。
if (::bind(socketListen, (LPSOCKADDR)&sin, sizeof(sin)) == SOCKET_ERROR)
{
std::cout << "绑定套接字失败,错误码:" << WSAGetLastError() << std::endl;
}
else
{
std::cout << "绑定套接字成功" << std::endl;
}
int nListenStatus = ::listen(socketListen, 10);
if (nListenStatus == SOCKET_ERROR)
{
std::cout << "监听套接字失败,错误码:" << WSAGetLastError() << std::endl;
}
else
{
std::cout << "监听套接字成功" << std::endl;
}
SOCKADDR_IN addrClient;
int nSize = sizeof(SOCKADDR);
SOCKET socketClient = accept(socketListen, (SOCKADDR*)&addrClient, &nSize);
char szSendBuffer[100];
sprintf(szSendBuffer, "欢迎IP:%s来到fengyuzaitu@51.cto", inet_ntoa(addrClient.sin_addr));//找对对应的IP并且将这行字打印到那里
//发送信息
send(socketClient, szSendBuffer, strlen(szSendBuffer) + 1, 0);
char szRecvBuffer[100];//接收
recv(socketClient, szRecvBuffer, strlen(szRecvBuffer) + 1, 0);
closesocket(socketClient);
closesocket(socketListen);
std::cout << "Hello World!\n";
}
头文件
#include <WinSock2.h>
#include <string>
#include <WS2tcpip.h>
#include <IPHlpApi.h>
#include <stdio.h>
#pragma comment(lib, "WS2_32.lib")
源代码
// 初始化 Winsock
WSADATA wsaData;
int iResult;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return NULL;
}
// 获取连接属性
struct addrinfo * result = NULL, *ptr = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo("192.168.0.18", "7002", &hints, &result);
//iResult = getaddrinfo("192.168.37.187", "7002", &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
WSACleanup();
return NULL;
}
// 创建 Socket 对象
ptr = result;
SOCKET ConnectSocket = INVALID_SOCKET;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if (ConnectSocket == INVALID_SOCKET) {
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return NULL;
}
// 链接
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
printf("Error at socket(): %ld\n", WSAGetLastError());
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
}
int nSendBuf = 32 * 1000;//设置为32K
setsockopt(ConnectSocket, SOL_SOCKET, SO_RCVTIMEO, (const char*)&nSendBuf, sizeof(int));
// Should really try the next address returned by getaddrinfo
// if the connect call failed
// But for this simple example we just free the resources
// returned by getaddrinfo and print an arror message
//freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return NULL;
}
send(ConnectSocket, strSendContext.c_str(), strSendContext.length(), 0);
char szbuffer[1024] = { 0 };
recv(ConnectSocket, szbuffer, 1024, 0);
::closesocket(ConnectSocket);
说明
当前内嵌代码进行自动化测试
编译错误
无法解析的外部符号 __imp__WSACloseEvent@4
解决
在cpp文件Include后添加 #pragma comment(lib,"ws2_32.lib")
'inet_addr': Use inet_pton() or InetPton() instead or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API warnings
解决
预处理器添加宏定义 _WINSOCK_DEPRECATED_NO_WARNINGS