Python 使用TCP\UDP协议创建一个聊天室

server端代码:

#encoding=utf-8
# 服务端代码
import socket

def server():
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = socket.gethostname()
    port = 12345
    server_socket.bind((host, port))
    server_socket.listen(5)

    print('等待客户端连接...')
    while True:
        client_socket, addr = server_socket.accept()
        print('连接地址:', addr)

        while True:
            message = client_socket.recv(1024).decode('utf-8')
            if not message:
                break
            print(f"客户端消息:{message}")

            # 服务端回复消息
            reply = input('回复客户端:')
            client_socket.send(reply.encode('utf-8'))

        client_socket.close()

if __name__ == '__main__':
    server()

Client端代码:

# 客户端代码
import socket

def client():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host='xxxxx'
    port = 12345
    client_socket.connect((host, port))

    while True:
        message = input('发送消息:')
        client_socket.send(message.encode('utf-8'))

        # 接收服务端消息
        server_message = client_socket.recv(1024).decode('utf-8')
        print(f"服务端消息:{server_message}")

    client_socket.close()

if __name__ == '__main__':
    client()

运行后的结果:

Client:

Server端:

host是主机的Device 名字

服务器与客户端建立 TCP 通信连接的交互过程:

UDP Server:

# UDP服务器端代码
import socket

# 创建套接字
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 绑定地址和端口
server_address = ('localhost', 12345)
server_socket.bind(server_address)

# 接收数据
data, client_address = server_socket.recvfrom(1024)
print(f"Received: {data.decode()} from {client_address}")

# 关闭套接字
server_socket.close()

UDP Client:

# UDP客户端代码
import socket

# 创建套接字
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

# 发送数据
message = "Hello, server!"
server_address = ('localhost', 12345)
client_socket.sendto(message.encode(), server_address)

# 关闭套接字
client_socket.close()

运行结果:

参考:Python网络编程实战指南:TCP协议探索与编程实例解析_python tcp-CSDN博客

        深入探讨Python网络编程:从基础到高级应用-腾讯云开发者社区-腾讯云 (tencent.com)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值