-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweek13_2_client.cpp
More file actions
41 lines (31 loc) · 954 Bytes
/
week13_2_client.cpp
File metadata and controls
41 lines (31 loc) · 954 Bytes
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
#include <cstdio>
#include <cstring>
#include <winsock.h>
#define MAXLINE 1024
int main() {
SOCKET sd;
struct sockaddr_in serv{};
char str[1024] = "How are you?";
char str_r[1024];
WSADATA wsadata;
WSAStartup(0x101, (LPWSADATA) &wsadata); // 呼叫 WSAStartup() 註冊 WinSock DLL 的使用
sd = socket(AF_INET, SOCK_STREAM, 0); //開啟一個 TCP socket.
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = inet_addr("127.0.0.1");
serv.sin_port = htons(5678);
connect(sd, (LPSOCKADDR) &serv, sizeof(serv)); // 連接至 echo server
printf("Client has connected to Server.\n");
while (true) { //每隔10秒,週期送出
Sleep(10000);
send(sd, str, int(strlen(str) + 1), 0);
printf("Send: %s (in 10 secs)\n", str);
recv (sd, str_r, MAXLINE, 0);
printf("Recv: %s \n" ,str);
if (strcmp(str, "exit") == 0) {
break;
}
}
closesocket(sd); //關閉TCP socket
WSACleanup(); // 結束 WinSock DLL 的使用
return 0;
}