import os
import platform

# 动态获取管道路径
def get_pipe_name():
    if platform.system() == "Windows":
        return r'\\.\pipe\python_run_pipe'  # Windows 命名管道路径
    else:
        return '/tmp/python_run_pipe'  # Linux 命名管道路径

PIPE_NAME = get_pipe_name()

def client():
    if platform.system() == "Windows":
        import win32file
        # Windows 使用 win32file 连接命名管道
        pipe = win32file.CreateFile(
            PIPE_NAME,
            win32file.GENERIC_READ | win32file.GENERIC_WRITE,
            0, None, win32file.OPEN_EXISTING, 0, None
        )
        print("Connected to server.")
        while True:
            # 输入消息
            message = input("Enter message: ")
            if not message:
                continue

            # 发送消息到服务端
            win32file.WriteFile(pipe, message.encode("utf-8"))

            # 接收服务端响应
            result, response = win32file.ReadFile(pipe, 4096)
            print(f"Received from server: {response.decode('utf-8').strip()}")
    else:
        # Linux 使用文件操作
        with open(PIPE_NAME, 'r+') as pipe:
            print("Connected to server.")
            while True:
                # 输入消息
                message = input("Enter message: ")
                if not message:
                    continue

                # 发送消息到服务端
                pipe.write(message + '\n')
                pipe.flush()

                # 接收服务端响应
                response = pipe.readline().strip()
                print(f"Received from server: {response}")

if __name__ == "__main__":
    client()