-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMySocket.cpp
More file actions
210 lines (182 loc) · 6.19 KB
/
Copy pathMySocket.cpp
File metadata and controls
210 lines (182 loc) · 6.19 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
#include <thread>
#include <unordered_map>
#include <mutex>
#include <string>
#include <iostream>
#include <cstring>
#include <queue>
#include "Core.hpp"
class MySocket {
public:
std::stringstream sin; // 收到的資料
std::stringstream sout; // 要傳送的資料
MySocket() : server_fd(-1) {}
~MySocket() {
if (server_fd != -1) {
close(server_fd);
}
for (auto& [_, fd] : clients) {
close(fd);
}
}
// Host Function: 開啟伺服器
void host(int port) {
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd < 0) {
perror("Socket creation failed");
return;
}
sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port);
// addr reuse
int opt = 1;
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
if (bind(server_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("Bind failed");
close(server_fd);
return;
}
if (listen(server_fd, 5) < 0) {
perror("Listen failed");
close(server_fd);
return;
}
std::cout << "Server listening on port " << port << std::endl;
// Accept new clients
std::thread(&MySocket::acceptClients, this).detach();
// Broadcast loop
std::thread(&MySocket::broadcastLoop, this).detach();
}
// Connect Function: 作為客戶端連線到伺服器
bool connect(const std::string& ip, int port) {
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd < 0) {
perror("Socket creation failed");
return false;
}
sockaddr_in server_addr{};
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(port);
if (inet_pton(AF_INET, ip.c_str(), &server_addr.sin_addr) <= 0) {
perror("Invalid address/Address not supported");
close(sock_fd);
return false;
}
if (::connect(sock_fd, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0) {
perror("Connection failed");
close(sock_fd);
return false;
}
std::cout << "Connected to server " << ip << ":" << port << std::endl;
// 接收資料的執行緒
std::thread([this, sock_fd]() {
char buffer[1024];
while (true) {
memset(buffer, 0, sizeof(buffer));
int bytes_received = recv(sock_fd, buffer, sizeof(buffer), 0);
if (bytes_received <= 0) {
std::cerr << "Server connection lost." << std::endl;
close(sock_fd);
break;
}
std::lock_guard<std::mutex> lock(sin_mutex);
sin << buffer;
}
}).detach();
// 傳送資料的執行緒
std::thread([this, sock_fd]() {
while (true) {
std::string data;
{
std::lock_guard<std::mutex> lock(sout_mutex);
data = sout.str().c_str();
sout.str("");
sout.clear();
}
if (!data.empty()) {
send(sock_fd, data.c_str(), data.size(), 0);
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}).detach();
return true;
}
int server_fd; // Server socket file descriptor
std::unordered_map<int, int> clients; // 客戶端的連線
std::queue<int> joined, leaved;
std::mutex clients_mutex; // 保護 clients 資料結構
std::mutex sin_mutex; // 保護 sin
std::mutex sout_mutex; // 保護 sout
// 接受客戶端連線
void acceptClients() {
while (true) {
sockaddr_in client_addr;
socklen_t addr_len = sizeof(client_addr);
int client_fd = accept(server_fd, (struct sockaddr*)&client_addr, &addr_len);
if (client_fd < 0) {
perror("Accept failed");
continue;
}
{
std::lock_guard<std::mutex> lock(clients_mutex);
clients[client_fd] = client_fd;
joined.push(client_fd);
rpf::Core::CORE->joined.push_back(client_fd);
}
std::cout << "New client connected." << std::endl;
// 處理客戶端資料
std::thread(&MySocket::handleClient, this, client_fd).detach();
}
}
// 處理客戶端資料
void handleClient(int client_fd) {
char buffer[1024];
while (true) {
memset(buffer, 0, sizeof(buffer));
int bytes_received = recv(client_fd, buffer, sizeof(buffer), 0);
if (bytes_received <= 0) {
std::cerr << "Client disconnected." << std::endl;
close(client_fd);
{
std::lock_guard<std::mutex> lock(clients_mutex);
clients.erase(client_fd);
leaved.push(client_fd);
rpf::Core::CORE->leaved.push_back(client_fd);
}
break;
}
// 廣播收到的訊息
{
std::lock_guard<std::mutex> lock(sin_mutex);
sin << buffer;
}
}
}
// 廣播伺服器收到的資料
void broadcastLoop() {
while (true) {
std::string data;
{
std::lock_guard<std::mutex> lock(sout_mutex);
data = sout.str().c_str();
sout.str("");
sout.clear();
}
if (!data.empty()) {
std::lock_guard<std::mutex> lock(clients_mutex);
for (const auto& [_, client_fd] : clients) {
send(client_fd, data.c_str(), data.size(), 0);
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
};