【Linux 编程基础 · 进程间通信 · 命名管道 · 消息队列】众所周知,网络游戏有服务端与客户端,客户端需要发 “消息” 给服务端,请使用 “命名管道” 模拟以下服务端和客户端的功能

题目

众所周知,网络游戏有服务端与客户端,客户端需要发 “消息” 给服务端,请使用 “命名管道” 模拟以下服务端和客户端的功能。

客户端:接收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>
#
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值