作业。。。

使用TCP协议完成两台主机之间的消息通信

import socket

 

 

# 服务器端代码

def server(host, port):

    # 创建socket对象

    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定IP地址和端口号

    server_socket.bind((host, port))

    # 监听客户端连接

    server_socket.listen(1)

 

    print("服务器已启动,等待客户端连接...")

 

    while True:

        # 等待客户端连接

        client_socket, addr = server_socket.accept()

        print("客户端已连接:", addr)

 

        # 接收客户端发送的数据

        data = client_socket.recv(1024).decode('utf-8')

        print("接收到的数据:", data)

 

        # 发送响应数据到客户端

        response = "Hello, I'm the server!"

        client_socket.sendall(response.encode('utf-8'))

 

        # 关闭连接

        client_socket.close()

 

 

# 客户端代码

def client(host, port):

    # 创建socket对象

    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

 

    try:

        # 连接服务器

        client_socket.connect((host, port))

        print("成功连接服务器!")

 

        # 发送数据到服务器

        message = "Hello, I'm the client!"

        client_socket.sendall(message.encode('utf-8'))

 

        # 接收服务器返回的响应数据

        response = client_socket.recv(1024).decode('utf-8')

        print("接收到的响应:", response)

    finally:

        # 关闭连接

        client_socket.close()

 

 

# 主函数

if __name__ == '__main__':

    host = '127.0.0.1' # 本地主机IP

    port = 8000 # 端口号

 

    # 启动服务器

    server(host, port)

 

    # 启动客户端(可选)

    # client(host, port)

使用UDP协议完成两台pc机之间的消息通信。

import socket

 

# 接收数据的线程函数

def receive_data(sock):

    while True:

        data, addr = sock.recvfrom(1024)

        print('接收到来自{}的消息:{}'.format(addr, data.decode('utf-8')))

 

# 主函数

if __name__ == '__main__':

    host = '127.0.0.1' # 本地主机IP

    port = 8000 # 端口号

    

    # 创建socket对象

    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)

    

    # 绑定IP地址和端口号

    sock.bind((host, port))

    

    print("服务器已启动,等待客户端连接...")

    

    # 创建接收数据的线程并启动

    recv_thread = threading.Thread(target=receive_data, args=(sock,))

    recv_thread.start()

    

    while True:

        # 输入要发送的消息

        message = input("请输入要发送的消息:")

        

        if message.lower() == 'exit':

            break

        

        # 发送消息到指定IP地址和端口号

        sock.sendto(message.encode('utf-8'), (host, port))

    

    # 关闭socket连接

    sock.close()

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值