下面展示一些 内联代码片 。
(2021.9.1学习记录)用C语言搭建一个简易的交换数据服务器
服务端
#include<stdio.h>
#include<WinSock2.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET servSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN saddr;
saddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8080);
bind(servSock, (SOCKADDR *)&saddr, sizeof(SOCKADDR));
printf("等待客户端连接...\n");
listen(servSock, 20);
int len = sizeof(SOCKADDR);
SOCKADDR_IN caddr;
SOCKET clntSock = accept(servSock, (SOCKADDR*)&caddr, &len);
printf("客户端连接成功!\n");
while (true) {
char recvBuf[1000] = "";
recv(clntSock, recvBuf, 1000, 0);
printf("客户端发送的消息内容:%s\n", recvBuf);
char sen[1000] = "";
printf("请输入要向客户端发送的信息:");
gets_s(sen);
send(clntSock, sen, strlen(sen) + 1, 0);
}
closesocket(clntSock);
closesocket(servSock);
WSACleanup();
}
*客户端
#include<stdio.h>
#include<winsock2.h>
#pragma comment(lib,"ws2_32.lib")
void main()
{
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
SOCKET clientSock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN saddr;
saddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");
saddr.sin_family = AF_INET;
saddr.sin_port = htons(8080);
bool i=connect(clientSock, (SOCKADDR *)&saddr,sizeof(SOCKADDR));
if (i == 0)
printf("服务端连接成功!\n");
else
{
printf("服务端连接失败,请重新尝试\n");
return;
}
while(true){
char sen[1000] = "";
printf("请输入要向服务端发送的信息:");
gets_s(sen);
send(clientSock, sen, strlen(sen) + 1, 0);
char recvBuf[1000] = "";
recv(clientSock, recvBuf, 1000, 0);
printf("服务端发送的消息内容:%s\n", recvBuf);
}
closesocket(clientSock);
WSACleanup();
}
|