-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.cpp
93 lines (60 loc) · 1.48 KB
/
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
87
88
89
90
91
92
#include <iostream>
#include <WS2tcpip.h>
#include <string>
#pragma comment (lib, "ws2_32.lib")
using namespace std;
int main()
{
string ip = "127.0.0.1";
// initialze winsock
WSADATA wsData;
WORD ver = MAKEWORD(2, 2);
int wsOk = WSAStartup(ver, &wsData);
if (wsOk != 0) {
cerr << "Cant initilize winsock, quitting" << endl;
return 1;
}
// create a socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
cerr << "Cant create socket, quitting" << endl;
WSACleanup();
return 1;
}
// bind socket
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(4444);
inet_pton(AF_INET, ip.c_str(), &hint.sin_addr);
// connect to server
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR) {
cerr << "Cant connect to server, Err #" << WSAGetLastError() << endl;
closesocket(sock);
WSACleanup();
return 1;
}
// while loop: accpet and echo message back to client
char buf[4096];
char buf2[1024] = "nice";;
while (true) {
ZeroMemory(buf, 4096);
//wait for client to send data
send(sock, buf2, sizeof(buf2), 0);
int bytesRecv = recv(sock, buf, 4096, 0);
cout << buf << endl;
if (bytesRecv == SOCKET_ERROR) {
cerr << "Error in recv(), Quitting" << endl;
break;
}
if (bytesRecv == 0) {
cout << "Client disconnected" << endl;
break;
}
// echo message back to client
}
// close socket
closesocket(sock);
// cleanup winsock
WSACleanup();
}