-
Notifications
You must be signed in to change notification settings - Fork 0
/
Server.cpp
68 lines (56 loc) · 2.15 KB
/
Server.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
#include <iostream>
#include <string>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8888
#define BUFFER_SIZE 1024
int main() {
WSADATA wsaData;
SOCKET serverSocket;
struct sockaddr_in serverAddress, clientAddress;
int clientAddressSize = sizeof(clientAddress);
char buffer[BUFFER_SIZE];
// Initialize Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize Winsock" << std::endl;
return -1;
}
// Create socket
serverSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket: " << WSAGetLastError() << std::endl;
WSACleanup();
return -1;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = INADDR_ANY;
serverAddress.sin_port = htons(PORT);
// Bind the socket to the specified address and port
if (bind(serverSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
std::cerr << "Failed to bind socket: " << WSAGetLastError() << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
std::cout << "Server listening on port " << PORT << std::endl;
while (true) {
// Receive data from client
int recvResult = recvfrom(serverSocket, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&clientAddress, &clientAddressSize);
if (recvResult == SOCKET_ERROR) {
std::cerr << "Failed to receive data: " << WSAGetLastError() << std::endl;
break;
}
// Print received data
std::cout << "Received from client: " << buffer << std::endl;
// Echo the received data back to the client
int sendResult = sendto(serverSocket, buffer, recvResult, 0, (struct sockaddr*)&clientAddress, clientAddressSize);
if (sendResult == SOCKET_ERROR) {
std::cerr << "Failed to send data: " << WSAGetLastError() << std::endl;
break;
}
}
// Cleanup
closesocket(serverSocket);
WSACleanup();
return 0;
}