python网络编程-socket样例
socket样例
一:只能一个客户端发送一个信息。
客户端 # -*- coding:utf-8 -*- __author__ = 'shisanjun' import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)#声明socket对象 sock.connect(("127.0.0.1",9696))#链接服务器端 sock.send("中国我爱你aaaabbbb".encode("utf-8")) #给服务器端发送消息,发送数据只能是byte类型 data1=sock.recv(4096)#接受服务器端发过来的数据 print(data1.decode("utf-8")) print("11111111111") sock.close() 服务端 # -*- coding:utf-8 -*- __author__ = 'shisanjun' import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind(("127.0.0.1",9696)) #绑定ip和端口 sock.listen(5) #监听 print("接受前") conn,addr=sock.accept() #阻塞等客服端消息
print("接受后") data = conn.recv(4096)
“”“
recv 官方建议最大8192 ,默认是阻塞的,客服端没有数据就是阻塞,如果客户
断开,conn,recv收到就是都是空数据,就会进入死循环,解决
if not data:
break
”“”
print(data.decode("utf-8")) conn.send(data.upper()) sock.close()
二:只能一个客户端发送N多消息
客户端 # -*- coding:utf-8 -*- __author__ = 'shisanjun' import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect(("127.0.0.1",9696)) while True: say=input("请输入文字>>") sock.send(say.encode("utf-8")) data1=sock.recv(4096) print(data1.decode("utf-8")) if say=='b': break sock.close() 服务器端 # -*- coding:utf-8 -*- __author__ = 'shisanjun' import socket sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.bind(("127.0.0.1",9696)) sock.listen(5) print("接受前") while True: conn,addr=sock.accept() while True: print("接受后") data = conn.recv(4096) print(data.decode("utf-8")) conn.send(data.upper()) sock.close()
三:多个客户端发送多个消息(实现文件上传功能)
客户端 # -*- coding:utf-8 -*- __author__ = 'shisanjun' import socket import json import os host=("127.0.0.1",9000) client=socket.socket() client.connect(host) while True: cmd_str=input("请输入命令>>").strip() if len(cmd_str)==0:continue cmd_list=cmd_str.split() if cmd_list[0]=="put": if len(cmd_list)==1: print("not find put filename") else: filename=cmd_list[1] if os.path.isfile(filename): file_obj=open(filename,'rb') filename2=filename.split("/")[-1] print(filename2) data_stat="%s %s" %(filename2,os.path.getsize(filename)) data={ "filename":filename2, "filesize":os.path.getsize(filename) } client.send(json.dumps(data).encode("utf-8")) for line in file_obj: client.send(line) file_obj.close() else: print("can not find file") elif cmd_list[0]=="get": pass 服务器端 # -*- coding:utf-8 -*- __author__ = 'shisanjun' import socket import json host=("127.0.0.1",9000) server=socket.socket() server.bind(host) server.listen(5) while True: conn,addr=server.accept() data=conn.recv(4096) print(data.decode("utf-8")) data_dict=json.loads(data.decode("utf-8")) filename=data_dict.get("filename") f=open(filename,"wb") recesize=0 while recesize<data_dict.get("filesize"): recefile=conn.recv(4096) f.write(recefile) recesize+=len(recefile) f.close()