4.20作业

服务端
import socket

phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.bind(('127.0.0.1',8081))
phone.listen(5)
while True:
    conn,addr=phone.accept()
    while True:
        try:
            data=conn.recv(1024)
            if len(data)==0:
                break
            print(data.decode('utf-8'))
            conn.send(data.upper())
        except Exception:
            break

    conn.close()

客户端
import socket
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
phone.connect(('127.0.0.1',8081))

while True:
    msg=input('请输入想要发送的内容: ').strip()
    if len(msg)==0:continue
    phone.send(msg.encode('utf-8'))


    data=phone.recv(1024)
    print(data.decode('utf-8'))
phone.close()

  

服务端
import socket

server=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 数据报协议=》udp协议

server.bind(('127.0.0.1',8081))

while True:
    data,client_addr=server.recvfrom(1024)
    server.sendto(data.upper(),client_addr)


server.close()

客户端
import socket

client=socket.socket(socket.AF_INET,socket.SOCK_DGRAM) # 流式协议=》tcp协议

while True:
    msg=input('>>>: ').strip()
    client.sendto(msg.encode('utf-8'),('127.0.0.1',8081))
    res=client.recvfrom(1024)
    print(res)

client.close()

  

posted @ 2020-04-20 20:39  清轩挽长风  阅读(89)  评论(0编辑  收藏  举报