server.c
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
SOCKET server_socket = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in server_addr;
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(1234);
bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr));
listen(server_socket, 20);
char Buff[1024];
SOCKADDR client_addr;
memset(&client_addr, 0, sizeof(client_addr));
int nsize = sizeof(client_addr);
while (1)
{
SOCKET add_sock = accept(server_socket, (SOCKADDR*)&client_addr, &nsize);
int len = recv(add_sock, Buff, 1024, 0);
Buff[len] = '\0';
printf("收到数据:%s\n",Buff);
send(add_sock, Buff, strlen(Buff), 0);
closesocket(add_sock);
}
closesocket(server_socket);
WSACleanup();
return 0;
}
client.c
#define _CRT_SECURE_NO_WARNINGS
#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include
#include
#include
#include
#pragma comment(lib,"ws2_32.lib")
int main()
{
WSADATA wsadata;
WSAStartup(MAKEWORD(2, 2), &wsadata);
SOCKADDR_IN server_addr;
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
server_addr.sin_port = htons(1234);
while (1)
{
SOCKET client_sock = socket(AF_INET, SOCK_STREAM, 0);
connect(client_sock, (SOCKADDR*)&server_addr, sizeof(server_addr));
char Buff[1024];
printf("请输入发送的消息:");
scanf("%s", Buff);
send(client_sock, Buff, strlen(Buff), 0);
memset(Buff, 0, 1024);
int len = recv(client_sock, Buff, 1024, 0);
Buff[len] = '\0';
printf("收到的数据:%s\n",Buff);
closesocket(client_sock);
}
WSACleanup();
return 0;
}