-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathweek_14_2_client.cpp
86 lines (71 loc) · 1.93 KB
/
week_14_2_client.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
/*
* NCYU 109 Network Programming
* Chat room server multiple thread client
* Created by linwebs on 2021/5/24.
*/
#include <iostream>
#include <cstring>
#include <winsock.h>
#define MAX_LINE 1024
using namespace std;
int main() {
SOCKET sd1, sd2;
sockaddr_in server{};
char str[1024] = "I love NP!";
WSADATA wsadata;
int conn_status;
int send_status;
int recv_status;
// Call WSAStartup() to Register "WinSock DLL"
WSAStartup(0x101, (LPWSADATA) &wsadata);
sd1 = socket(AF_INET, SOCK_STREAM, 0);
sd2 = socket(AF_INET, SOCK_STREAM, 0);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(5678);
// connect to server
conn_status = connect(sd1, (LPSOCKADDR) &server, sizeof(server));
if (conn_status == SOCKET_ERROR) {
cout << "connect() failed" << endl;
}
conn_status = connect(sd2, (LPSOCKADDR) &server, sizeof(server));
if (conn_status == SOCKET_ERROR) {
cout << "connect() failed" << endl;
}
while (true) {
strcpy(str, "I love NP!\n");
send_status = send(sd1, str, int(strlen(str) + 1), 0); // send to server
if (send_status == SOCKET_ERROR) {
cout << "send() failed" << endl;
break;
}
cout << "send: " << str;
Sleep(1000);
recv_status = recv(sd1, str, MAX_LINE, 0); // receive data from server
if (recv_status == SOCKET_ERROR) {
cout << "recv() failed" << endl;
break;
}
cout << "recv: " << str;
strcpy(str, "I love Algorithm!\n");
send_status = send(sd2, str, int(strlen(str) + 1), 0); // send to server
if (send_status == SOCKET_ERROR) {
cout << "send() failed" << endl;
break;
}
cout << "send: " << str;
Sleep(1000);
recv_status = recv(sd2, str, MAX_LINE, 0); // receive data from server
if (recv_status == SOCKET_ERROR) {
cout << "recv() failed" << endl;
break;
}
cout << "recv: " << str;
}
// close TCP socket
closesocket(sd1);
closesocket(sd2);
// finish "WinSock DLL"
WSACleanup();
return 0;
}