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

server端代码:

python 复制代码
#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端代码:

python 复制代码
# 客户端代码
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:

python 复制代码
# 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:

python 复制代码
# 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)

相关推荐
waterHBO37 分钟前
python 爬虫 selenium 笔记
爬虫·python·selenium
kejijianwen1 小时前
JdbcTemplate常用方法一览AG网页参数绑定与数据寻址实操
服务器·数据库·oracle
编程零零七2 小时前
Python数据分析工具(三):pymssql的用法
开发语言·前端·数据库·python·oracle·数据分析·pymssql
suifen_3 小时前
RK3229_Android9.0_Box 4G模块EC200A调试
网络
铁松溜达py3 小时前
编译器/工具链环境:GCC vs LLVM/Clang,MSVCRT vs UCRT
开发语言·网络
AIAdvocate4 小时前
Pandas_数据结构详解
数据结构·python·pandas
小言从不摸鱼4 小时前
【AI大模型】ChatGPT模型原理介绍(下)
人工智能·python·深度学习·机器学习·自然语言处理·chatgpt
Karoku0665 小时前
【网站架构部署与优化】web服务与http协议
linux·运维·服务器·数据库·http·架构
geek_Chen015 小时前
虚拟机共享文件夹开启后mnt/hgfs/下无sharefiles? --已解决
linux·运维·服务器
FreakStudio6 小时前
全网最适合入门的面向对象编程教程:50 Python函数方法与接口-接口和抽象基类
python·嵌入式·面向对象·电子diy