注册 登录
编程论坛 Python论坛

Pygame实现联机

风卷浪起 发布于 2024-05-13 22:13, 599 次点击
如题
3 回复
#2
yiyanxiyin2024-05-14 09:43
联机一般使用socket
#3
风卷浪起2024-05-15 21:03
所以如何操作?
#4
apull2024-05-16 08:57
简单聊天室示例
服务端
程序代码:

import socket  
  
def start_server():  
    server_address = ('localhost', 9527)  
  
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:  
        sock.bind(server_address)  
        sock.listen(1)  
  
        while True:  
            print('等待连接...')  
            connection, client_address = sock.accept()  
  
            try:  
                print(f'客户端 {client_address} 已连接')  
  
                while True:  
                    data = connection.recv(16)  
                    if not data:  
                        break  
                    print(f'收到 "{data.decode()}"')  
                    connection.sendall(data)  # 简单地回显收到的数据  
  
            finally:  
                connection.close()  
  
if __name__ == '__main__':  
    start_server()


客户端
程序代码:

import socket  
  
def start_client():  
    server_address = ('localhost', 9527)  
  
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:  
        sock.connect(server_address)  
  
        try:  
            while True:  
                message = input('>> ')  
                if message.lower() == 'q':  
                    break  
                sock.sendall(message.encode())  
                data = sock.recv(1024)  
                print(f'收到: "{data.decode()}"')  
  
        finally:  
            print('关闭连接')  
            sock.close()  
  
if __name__ == '__main__':  
    start_client()

可以通过修改互相发送的内容进行复杂操作。
1