day18-作业

作业:

  1. 客户端和服务器聊天,可以一直聊天,直到一方发送’拜拜’。然后就可以和下一个人一直聊
import socket

#套接字
server = socket.socket()
#绑定地址
server.bind(('10.7.187.62',8051))
#监听
server.listen(512)
print('go go')

while True:
    # 接收客户端发送的请求,返回建立的会话和客户端的地址
    conversation,addr = server.accept()
    while True:
        #接收
        data = conversation.recv(1024)
        if data.decode('utf-8') != '拜拜':
            print('客户端:',data.decode('utf-8'))
        else:
            break
        #发送
        message = input('服务器:')
        conversation.send(message.encode('utf-8'))
        if message == '拜拜':
            break
    #
    conversation.close()
    print('开始下一个聊天')
import socket

#套接字
client = socket.socket()

#连接地址
client.connect(('10.7.187.62',8051))

while True:

    #发送
    message = input('客户端:')
    client.send(message.encode('utf-8'))
    if message == '拜拜':
        break
    #接收
    data = client.recv(1024)
    if data.decode('utf-8') != '拜拜':
        print('服务器:', data.decode('utf-8'))
    else:
        break

2.客户端给服务器发送请求,请求成功后,客户端给服务发送‘1’,服务器就给客户端发送一张图片;客户端给服务发送‘2’,服务器就给客户端返回一个json文件中的内容;客户端给服务发送‘3’, 服务器返回’拜拜’,然后断开连接

import socket
import requests
server = socket.socket()
server.bind(('10.7.187.62',8052))
server.listen(512)
print('ok 开始吧!')



while True:
    conversation,addr = server.accept()
    data = conversation.recv(1024)
    #接收1发送一张图片
    if data.decode('utf-8') == '1':
        with open('1.jpg','br') as f:
            content = f.read()
            conversation.send(content)
            conversation.close()


    # #接收2 一个json文件中的内容
    if data.decode('utf-8') == '2':
        with open('1.json','br') as f:
            content = f.read()
            conversation.send(content)
            conversation.close()

    #接收3 拜拜
    if data.decode('utf-8') == '3':
        message = '拜拜'
        conversation.send(message.encode('utf-8'))
        break
import socket
#套接字
client = socket.socket()

# #连接地址
client.connect(('10.7.187.62',8052))
#请求
# url = 'http://52.80.135.246/'
# url = 'http://10.7.187.62'
# response = requests.get(url)
# print(response)

while True:
    #发送
    message = input('客户端(1~3):')
    client.send(message.encode('utf-8'))
    #接收1
    if message == '1':
        data = bytes()
        while True:
            re_data = client.recv(1024)
            data += re_data
            print('接收到数据')
            if not re_data:
                break

        print('数据接收完了!!!!!')
        with open('new.jpg','bw') as f:
            f.write(data)
            break

    # # 接收2
    if message == '2':
        data = client.recv(1024)
        with open('new1.json','w',encoding='utf-8') as f:
            f.write(data.decode('utf-8'))
            break

    #接收3
    if message == '3':
        data = client.recv(1024)
        print(data.decode('utf-8'))
        if data.decode('utf-8') != '拜拜':
            print('服务器:', data.decode('utf-8'))
        else:
            break

你可能感兴趣的:(day18-作业)