#include <winsock.h> #include <iostream>
#pragma comment(lib, "WSOCK32.lib")
using namespace std;
typedef struct umsg { int cursor_pos_x; int cursor_pos_y; int cursor_key_state;
umsg() :cursor_pos_x(), cursor_pos_y(), cursor_key_state() { cursor_pos_x = 0; cursor_pos_y = 0; cursor_key_state = 0; } }umsg;
int GetKeyState() { if (GetAsyncKeyState(VK_LBUTTON) & 0x8000) { Sleep(15); return 1; } if (GetAsyncKeyState(VK_RBUTTON) & 0x8000) { Sleep(15); return 2; } return 0; }
int main(int argc, char *argv[]) { WSADATA wsaData; struct sockaddr_in addr; int fd; struct ip_mreq mreq;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { std::cout << "初始化失败" << std::endl; return 0; }
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { std::cout << "套接字创建失败" << std::endl; return 0; }
u_int yes = 1; if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char *)&yes, sizeof(yes)) < 0) { std::cout << "设置组播模式失败" << std::endl; return 0; }
UCHAR uLoop = 1;
setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, (char*)&uLoop, sizeof(uLoop));
memset(&addr, 0, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(9999);
if (bind(fd, (struct sockaddr *) &addr, sizeof(addr)) < 0) { std::cout << "绑定失败" << std::endl; return 0; }
mreq.imr_multiaddr.s_addr = inet_addr("228.2.3.1"); mreq.imr_interface.s_addr = htonl(INADDR_ANY); if (setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (char *)&mreq, sizeof(mreq)) < 0) { int err = GetLastError(); std::cout << "设置组失败: " << err << std::endl; return 0; }
while (1) { char recv_buffer[4096] = { 0 }; char send_buffer[4096] = { 0 }; int addrlen = sizeof(addr); int nbytes;
if ((nbytes = recvfrom(fd, recv_buffer, 4096, 0, (struct sockaddr *) &addr, (int *)&addrlen)) < 0) { std::cout << "接收数据包失败" << std::endl; return 0; } recv_buffer[nbytes] = '\0'; std::cout << "接收组播数据包: " << recv_buffer << std::endl;
umsg msg;
POINT pt; BOOL ref = GetCursorPos(&pt);
msg.cursor_pos_x = pt.x; msg.cursor_pos_y = pt.y;
int key_flag = GetKeyState(); if (key_flag == 0) { msg.cursor_key_state = 0; } else if (key_flag == 1) { msg.cursor_key_state = 1; } else if (key_flag == 2) { msg.cursor_key_state = 2; }
std::cout << "鼠标X = " << msg.cursor_pos_x << " 鼠标Y = " << msg.cursor_pos_y << std::endl; std::cout << "鼠标键位 = " << msg.cursor_key_state << std::endl;
sendto(fd, (char *)&msg, 4096, 0, (struct sockaddr *) &addr, sizeof(addr)); } return 0; }
|