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‘))
相关推荐
书虫媛 2020-05-03
CloudXli 2020-04-20
架构技术交流 2020-04-14
fsl 2020-07-04
fibbery学习笔记 2020-06-27
MAC2007 2020-06-06
lenchio 2020-03-27
SoarFly00 2020-02-11
OwenJi 2020-01-17
Ongoingcre 2013-04-01
bapinggaitianli 2019-12-19
qscool 2019-12-23
furongwei 2019-12-17
typhoonpython 2019-12-11
sapliang 2019-12-10
huangzonggui 2019-12-09
kevinli 2019-12-09
leodengzx 2019-12-01
王道立心 2019-11-19