python 36 套接字编程

一,基于tcp协议的套接字编程

客户端:

import socket


#  1,买手机
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

#  2,请求连接
phone.connect((‘127.0.0.1‘,8082))

#  3,通信
while True:
    msg=input(‘请输入发送文字:‘).strip()
    if len(msg) == 0: continue
    phone.send(msg.encode(‘utf8‘))
    if msg == "q": break
    data=phone.recv(1024)
    print(data.decode(‘utf8‘))


#  5,关机
phone.close()

服务端:

import socket

#  1,买电话()
phone=socket.socket(socket.AF_INET,socket.SOCK_STREAM)


#  2,装电话卡
phone.bind((‘127.0.0.1‘,8082))

#  3,开机
phone.listen(5)

#  4,等待电话请求
while True:
    conn,client_addr=phone.accept()

    #  5,通信(ulinx系统遇到客户端突然断开连接会进入循环,用break可以打断)
    while True:
        try:
            data=conn.recv(1024)
            if data.decode(‘utf8‘) == ‘q‘:break
            conn.send(data.upper())
        except Exception:
            break


    #  6,挂机
    conn.close()

#  7,关机
# phone.close()

二,基于udp协议的编程

服务端:

import socket
sever=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)

sever.bind((‘127.0.0.1‘,8083))
while True:
    date,user_addr=sever.recvfrom(1024)
    date=date.upper()
    sever.sendto(date,user_addr)

客户端:

import socket

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

while True:
    msg=input(‘请输入:‘).strip()
    client.sendto(msg.encode(‘utf8‘),(‘127.0.0.1‘,8083))
    res,sever_addr=client.recvfrom(1024)
    print(res.decode(‘utf8‘))

相关推荐