-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsend_many_text_server.cpp
114 lines (79 loc) · 2.03 KB
/
send_many_text_server.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
* NCYU 109 Network Programming
* Exercise 5: tcp send many text server
* Created by linwebs on 2021/5/3.
*/
#include <iostream>
#include <winsock.h>
#define MAXLINE 1024
#define LISTEN_NUM 5
using namespace std;
int main() {
SOCKET sd;
SOCKET sd_client;
WSADATA wsadata;
struct sockaddr_in serv{};
struct sockaddr_in client{};
FILE *file_out;
char str_recv[MAXLINE];
// server's ip address
const char server_ip[16] = "127.0.0.1";
// server's port number
u_short server_port = 5678;
// bind status
int bind_status;
// listen status
int listen_status;
// serv bytes
int serv_len;
// client bytes
int client_len;
// receive bytes
int recv_len = 0;
// Include sockaddr_ing struct (serv)
serv.sin_family = AF_INET;
// server's ip address
serv.sin_addr.s_addr = inet_addr(server_ip);
// server's port number
// htons: host to network
serv.sin_port = htons(server_port);
// write and overwrite the file
file_out = fopen("out.txt", "w+t");
// Call WSAStartup() to Register "WinSock DLL"
WSAStartup(0x101, (LPWSADATA) &wsadata);
// Open a TCP socket
sd = socket(AF_INET, SOCK_STREAM, 0);
cout << "sd: " << sd << endl;
serv_len = sizeof(serv);
// bind client
bind_status = bind(sd, (struct sockaddr *) &serv, serv_len);
if (bind_status == SOCKET_ERROR) {
cout << "bind function failed with error: " << WSAGetLastError() << endl;
closesocket(sd);
WSACleanup();
return 1;
}
cout << "bind: " << bind_status << endl;
listen_status = listen(sd, LISTEN_NUM);
cout << "listen: " << listen_status << endl;
client_len = sizeof(client);
sd_client = accept(sd, (struct sockaddr *) &client, &client_len);
// receive from server
while (true) {
recv_len = recv(sd_client, str_recv, 50, 0);
if(recv_len == 0) {
break;
}
str_recv[recv_len] = '\0';
cout << "receive: " << str_recv << "(" << recv_len << " bytes)" << endl;
fputs(str_recv, file_out);
}
// close file
fclose(file_out);
// close TCP socket
closesocket(sd);
// finish "WinSock DLL"
WSACleanup();
//system("pause");
return 0;
}