socket套接字

此代码是客户端发往服务器端,是单向的

 

服务器端:
#服务器端(接收)
#-*- coding: UTF-8 -*-
import socket,time,SocketServer,struct,os,thread
host='192.168.56.1'
port=1234
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #定义socket类型
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
#用bind();listen();
s.bind((host,port))
s.listen(1)
i = 696
def conn_thread(connection,address): 
    global i
    while True:
        try:
            connection.settimeout(1200)
            fileinfo_size=struct.calcsize('=128sl') 
            buf = connection.recv(fileinfo_size)
            if buf: #如果不加这个if,第一个文件传输完成后会自动走到下一句
                print 1
                filename,filesize =struct.unpack('=128sl',buf) 
                print 2
                filename_f = filename.strip('\00')
                j = i   
                filenewname = filename_f + '_' +str(j)
                i = i + 1
                print 'file new name is %s, filesize is %s' %(filenewname,filesize)
                recvd_size = 0 #定义接收了的文件大小
                file = open(filenewname,'wb')
                print 'stat receiving...'
                while not recvd_size == filesize:
                    if filesize - recvd_size > 1024:
                        rdata = connection.recv(1024)
                        recvd_size += len(rdata)
                    else:
                        rdata = connection.recv(filesize - recvd_size) 
                        recvd_size = filesize
                    file.write(rdata)
                file.close()
                print 'receive done'
        except socket.timeout:
            connection.close()
while True:
    connection,address=s.accept()
    print('Connected by ',address)
    thread.start_new_thread(conn_thread,(connection,address)) 
s.close()


#客户端(发送)

#客户端
#-*- coding: UTF-8 -*-
import socket,os,struct
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#客户端用connect(IP,端口)
s.connect(('192.168.56.1',1234))
def Send():
    filepath = "C:\\xubing\\record\\record"
    if os.path.isfile(filepath):
        fileinfo_size=struct.calcsize('128sl') #定义打包规则
        #定义文件头信息,包含文件名和文件大小
        fhead = struct.pack('128sl',os.path.basename(filepath),os.stat(filepath).st_size)
        s.send(fhead)
        fo = open(filepath,'rb')
        while True:
            filedata = fo.read(1024)
            if not filedata:
                break
            s.send(filedata)
        fo.close()
        print 'send over...'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值