从服务器(C++TCP客户端)接收数据时,如何在后台检测键盘事件



我正在用C++制作一个客户端和服务器之间的TCP连接的多人游戏。客户端用于检测控制台中的按键(箭头键(并将数据发送到服务器。服务器应该向所有连接的客户端发送有关球员位置等的数据。这意味着我需要随时从服务器接收数据,同时检测何时按下箭头键,以便将数据发送回服务器。如何在监听keyevent的同时接收数据?

我尝试了以下操作,但是循环在_getch((处卡住了;其等待输入。

int keyListener() {
int keypress = _getch();
return keypress;

}

int main(({

int c = 0;
bool run = true;
while (run) {
cout << "Listening to socket" << endl;

c = keyListener();
switch (c) {
case KEY_UP:
cout << "UP" << endl;
break;
case KEY_DOWN:
cout << "DOWN" << endl;
break;
case KEY_LEFT:
cout << "LEFT" << endl;
break;
case KEY_RIGHT:
cout << "RIGHT" << endl;
break;
default:
cout << "Listening for keypress" << endl;
break;
}
}
return 0;

}

学习游戏开发需要不止一本书。我认为这只是一个C++编码练习;游戏";主题

我建议您创建两个线程:一个用于监听键盘输入,另一个用于处理TCP。你在游戏开始时启动这些线程,并在退出时加入它们。

过于简化的游戏骨架可能看起来像这样:

#include <atomic>
#include <thread>
#include <queue>
#include <mutex>
#include <conio.h>
std::atomic<bool> run = true;
std::queue<int> input;
std::mutex guard;  // to protects input queue
void keyboard()
{
while (run)
{
int keypress = _getch();
// TODO: if keypress indicates Exit - set run = false;
// Lock the queue for safe multi-thread access
{
const std::lock_guard<std::mutex> lock(guard);
input.push(keypress);
}
}
}
int main()
{
std::thread keyListener(keyboard);
// TODO: start your TCP thread
while (run)
{
// 1. Process input (keyboard, mouse, voice, etc.)
{
// Lock the queue for safe multi-thread access
const std::lock_guard<std::mutex> lock(guard);
// Pop all collected keys and process them
while (!input.empty())
{
int keypress = input.front();
input.pop();
// TODO: Send game-related keys to the TCP thread
}
}
// 2. Process TCP input, probably with another queue
// 3. Update the Game World
// 4. Display the Game World
}
keyListener.join();
// TODO: join your TCP thread
}

最新更新