-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
74 lines (62 loc) · 1.87 KB
/
main.cpp
File metadata and controls
74 lines (62 loc) · 1.87 KB
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
// Coded by Kirisan Manivannan
// Shoutout to: Sloan Kelly; https://www.youtube.com/watch?v=0Zr_0Jy8mWE
#include<iostream>
#include<string>
#include<ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
using namespace std;
void main() {
string ipAddress = "Type the IP address here"; // IP address of the srver
int port = 80; // Listening port #(number) on the server
// Initialize Winsock
WSAData data;
WORD ver = MAKEWORD(2, 2);
int wsResult = WSAStartup(ver, &data);
if (wsResult != 0) {
cerr << "Can't start winsock, Err #" << wsResult << endl;
return;
}
// Create socket
SOCKET sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
cerr << "Can't create socket, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Fill in a hint structure
sockaddr_in hint;
hint.sin_family = AF_INET;
hint.sin_port = htons(port);
inet_pton(AF_INET, ipAddress.c_str(), &hint.sin_addr);
// Connect to server
int connResult = connect(sock, (sockaddr*)&hint, sizeof(hint));
if (connResult == SOCKET_ERROR) {
cerr << "Can't connect to server, Err #" << WSAGetLastError() << endl;
WSACleanup();
return;
}
// Do-while loop to send and recive data
char buf[4096];
string userInput;
do {
// Prompt the user for some text
cout << "> ";
getline(cin, userInput);
if (userInput.size() > 0) {
// Send the text
int sendResult = send(sock, userInput.c_str(), userInput.size(), 0);
if (sendResult != SOCKET_ERROR) {
// Wait for response
ZeroMemory(buf, 4096);
int byteReceived = recv(sock, buf, 4096, 0);
if (byteReceived > 0) {
//Echo response to console
cout << "SERVER> " << string(buf, 0, byteReceived) << endl;
}
}
}
} while (userInput.size() > 0);
// Gracefully close down everything
closesocket(sock);
WSACleanup();
}