题目
众所周知,网络游戏有服务端与客户端,客户端需要发 “消息” 给服务端,请使用 “命名管道” 模拟以下服务端和客户端的功能。
客户端:接收4种输入‘w’、’s’、’a’、’d’ 键,他们分别对应了上、下、左、右移动,将接收的输入作为 “消息” 发送给服务端。
服务端:每隔一秒打印角色的坐标 (x, y),初始坐标为 (0, 0),服务端在接收到客户端的 “消息” 过后,重新计算角色的坐标。其中向上 y 加 1,向下 y 减 1,向左 x 减 1,向右 x 加 1。
源代码
命名管道
Client:
#include <cstdlib>
#include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
const char* const pipe_name = "pcsc";
int c;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int existent = access(pipe_name, F_OK);
if (existent == -1) {
int r = mkfifo(pipe_name, 0664);
if(r == -1) {
puts("mkfifo ERROR.");
exit(EXIT_FAILURE);
}
}
int pfd = open(pipe_name, O_WRONLY);
system("/bin/stty raw");
for (;;) {
c = getchar();
if (c == 't' || c == 'T') break;
write(pfd, &c, sizeof(int));
}
system("/bin/stty cooked");
close(pfd);
return 0;
}
Server:
#include <chrono>
#include <cstdlib>
#include <fcntl.h>
#include <iostream>
#include <sys/stat.h>
#