-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
105 lines (93 loc) · 2.28 KB
/
client.cpp
File metadata and controls
105 lines (93 loc) · 2.28 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
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
#include <iostream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include <vector>
#include <string>
using namespace std;
bool Initialize()
{
return true; // No WSAStartup needed in Linux
}
void SendMsg(int s, sockaddr_in servaddr)
{
cout << "Chat Name: " << endl;
string name;
getline(cin, name);
string message;
while (true)
{
getline(cin, message);
string msg = name + ": " + message;
int b = sendto(s, msg.c_str(), msg.length(), 0, (sockaddr *)&servaddr,
sizeof(servaddr));
if (b < 0)
{
cout << "Send failed" << endl;
break;
}
if (message == "quit")
{
cout << "Stopping application" << endl;
break;
}
}
close(s); // Use `close()` in Linux
}
void ReceiveMsg(int s)
{
char buffer[4096];
while (true)
{
int b = recvfrom(s, buffer, sizeof(buffer), 0, NULL, NULL);
if (b <= 0)
{
cout << "Disconnected" << endl;
break;
}
for (int i = 0; i < b; ++i)
{
printf("%02x ", (unsigned char)buffer[i]);
}
printf("\n");
string message(buffer, b);
cout << "Message from server: " << message << endl;
}
close(s); // Close socket
}
int main()
{
if (!Initialize())
{
cout << "Initialization failed" << endl;
return 0;
}
cout << "Client" << endl;
int s = socket(AF_INET, SOCK_DGRAM, 0);
if (s < 0)
{
cout << "Socket creation failed" << endl;
return 0;
}
string serveraddress = "127.0.0.1";
int port = 6969;
sockaddr_in serveraddr;
serveraddr.sin_family = AF_INET;
serveraddr.sin_port = htons(port);
inet_pton(AF_INET, serveraddress.c_str(), &(serveraddr.sin_addr));
if (connect(s, reinterpret_cast<sockaddr *>(&serveraddr), sizeof(serveraddr)) < 0)
{
cout << "Connection failed" << endl;
close(s);
return 0;
}
cout << "Connected" << endl;
thread senderThread(SendMsg, s, serveraddr);
thread receiverThread(ReceiveMsg, s);
senderThread.join();
receiverThread.join();
cout << "Client finished" << endl;
return 0;
}