参考
程序参考 Visual Studio 2019 C++实现socket通信,添加ws2_32.lib库,新手代码
我这做了微调
编译
编译 gcc client.c -lwsock32 -o client
,追加 -lwsock32
client.c
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
int main(int argv, char* argc[])
{
//初始化
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET clntSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
//向服务器发送消息
struct sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节都用0填充
sockAddr.sin_family = PF_INET;
sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sockAddr.sin_port = htons(8888);
connect(clntSock, (SOCKADDR*)& sockAddr, sizeof(SOCKADDR));
//接收服务器消息
char szBuffer[1024] = { 0 };
recv(clntSock, szBuffer, 1024, 0);
//输出接收到的数据
printf("服务端:%s\n", szBuffer);
//向服务端发送消息
const char* str = "hello server";
send(clntSock, str, strlen(str) + sizeof(char), 0);
//关闭套接字
closesocket(clntSock);
//终止dll
WSACleanup();
system("pause");
return 0;
}
server.c
#include <stdio.h>
#include <WinSock2.h>
#pragma comment(lib,"ws2_32.lib") //加载ws2_32.dll
int main(int argv, char* argc[])
{
//初始化
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
//创建套接字
SOCKET servSock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
//绑定套接字
struct sockaddr_in sockAddr;
memset(&sockAddr, 0, sizeof(sockAddr)); //每个字节用0填充
sockAddr.sin_family = PF_INET; //使用ipv4
sockAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
sockAddr.sin_port = htons(8888); //端口
bind(servSock, (SOCKADDR*)&sockAddr, sizeof(SOCKADDR));
//进入监听状态
listen(servSock, 20);
//接收客户端消息
SOCKADDR clntAddr;
int nSize = sizeof(SOCKADDR);
SOCKET clntSock = accept(servSock, (SOCKADDR*)&clntAddr, &nSize);
//向客户端发送消息
const char* str = "hello client";
send(clntSock, str, strlen(str) + sizeof(char), 0);
char szBuffer[1024] = { 0 };
recv(clntSock, szBuffer, 1024, 0);
printf("客户端:%s\n", szBuffer);
//关闭套接字
closesocket(clntSock);
closesocket(servSock);
//终止dll使用
WSACleanup();
system("pause");
return 0;
}