2022-04-22 15:46:25 +08:00
|
|
|
#include <stdio.h>
|
|
|
|
#include <string.h>
|
2022-04-22 16:12:14 +08:00
|
|
|
#include <stdbool.h>
|
2022-04-22 15:46:25 +08:00
|
|
|
#include <winsock2.h>
|
|
|
|
|
|
|
|
#define PORT 8888
|
|
|
|
#define BUFFER_SIZE 4196
|
|
|
|
|
|
|
|
const char* kExitFlag = "exit";
|
|
|
|
|
|
|
|
int main() {
|
|
|
|
WORD winsock_version = MAKEWORD(2,2);
|
|
|
|
WSADATA wsa_data;
|
|
|
|
if (WSAStartup(winsock_version, &wsa_data) != 0) {
|
|
|
|
printf("Failed to init socket dll!\n");
|
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2022-04-22 16:12:14 +08:00
|
|
|
SOCKET server_socket= socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
|
2022-04-22 15:46:25 +08:00
|
|
|
if (server_socket == INVALID_SOCKET) {
|
|
|
|
printf("Failed to create server socket!\n");
|
|
|
|
return 2;
|
|
|
|
}
|
|
|
|
|
2022-04-22 16:12:14 +08:00
|
|
|
struct sockaddr_in server_addr;
|
2022-04-22 15:46:25 +08:00
|
|
|
server_addr.sin_family = AF_INET;
|
|
|
|
server_addr.sin_port = htons(PORT);
|
|
|
|
server_addr.sin_addr.S_un.S_addr = INADDR_ANY;
|
|
|
|
|
|
|
|
if (bind(server_socket, (LPSOCKADDR)&server_addr, sizeof(server_addr)) == SOCKET_ERROR) {
|
|
|
|
printf("Failed to bind port!\n");
|
|
|
|
return 3;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (listen(server_socket, 10)) {
|
|
|
|
printf("Failed to listen!\n");
|
|
|
|
return 4;
|
|
|
|
}
|
|
|
|
|
2022-04-22 16:12:14 +08:00
|
|
|
struct sockaddr_in client_addr;
|
2022-04-22 15:46:25 +08:00
|
|
|
int client_addr_len = sizeof(client_addr);
|
|
|
|
printf("Wait for connecting...\n");
|
|
|
|
|
|
|
|
SOCKET client_socket = accept(server_socket, (SOCKADDR*)&client_addr, &client_addr_len);
|
|
|
|
if (client_socket == INVALID_SOCKET) {
|
|
|
|
printf("Failed to accept!\n");
|
|
|
|
return 5;
|
|
|
|
}
|
|
|
|
|
|
|
|
printf("Succeed to receive a connection: %s\n" , inet_ntoa(client_addr.sin_addr));
|
|
|
|
|
|
|
|
char recv_buf[BUFFER_SIZE+1];
|
|
|
|
while (true) {
|
|
|
|
int ret = recv(client_socket, recv_buf, BUFFER_SIZE, 0);
|
|
|
|
if (ret < 0) {
|
|
|
|
printf("Failed to receive data!\n");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
recv_buf[ret]=0; // correctly ends received string
|
|
|
|
|
|
|
|
printf("Receive from Client: \"%s\" \n", recv_buf);
|
2022-04-22 16:12:14 +08:00
|
|
|
if (strcmp(kExitFlag,recv_buf)==0) {
|
2022-04-22 15:46:25 +08:00
|
|
|
printf("Exit!\n");
|
|
|
|
break;
|
|
|
|
}
|
|
|
|
|
2022-04-22 16:12:14 +08:00
|
|
|
const char* send_data = "Hello, Tcp Client!";
|
2022-04-22 15:46:25 +08:00
|
|
|
send(client_socket, send_data, strlen(send_data), 0);
|
|
|
|
}
|
|
|
|
|
|
|
|
closesocket(client_socket);
|
|
|
|
closesocket(server_socket);
|
|
|
|
|
|
|
|
WSACleanup();
|
|
|
|
|
|
|
|
return 0;
|
|
|
|
}
|