啊峰哥

1.6socket服务器传送文件--gui窗口

socket服务器代码

import sys,os,time,_thread
from socket import *

class Server(object):
    def __init__(self):                      #用于初始化端口和IP
        self.host = 'localhost'
        self.port = 50001
        self.server()

    def now(self):                           #返回当前时间   
        return time.asctime()

    def server_thread(self,conn):            #多线程运行服务器
        sockfile = conn.makefile('r')
        filename = sockfile.readline()[:-1]
        try:  # 读取文件内容,并传输
            file = open(filename, 'rb')
            while True:
                bytes = file.read(1024)
                if not bytes: break
                sent = conn.send(bytes)
                assert sent == len(bytes)
        except:
            print('Error downloading file on server:', filename)
        conn.close()

    def server(self):                         #开启线程
        sock = socket(AF_INET, SOCK_STREAM)
        sock.bind((self.host, self.port))
        sock.listen(5)
        while True:
            conn, addr = sock.accept()
            print('Server connect by', addr, 'at', self.now())
            _thread.start_new_thread(self.server_thread, (conn,))  




Server()

 

socket客户端代码

利用tkinter打印出界面,在界面内设置IP端口和文件,并设置提交函数

import sys,os,time,_thread
from socket import *
from tkinter import *
from tkinter.messagebox import showinfo

class Client(object):
    def __init__(self):
        pass

    def now(self):
        return time.asctime()

    def client(self,host,port,filename):               #客户端运行
        sock = socket(AF_INET, SOCK_STREAM)
        sock.connect((host, port))
        sock.send((filename + '\n').encode())

        dropdir = 'New ' + os.path.split(filename)[1]  # 获取文件地址,保存在默认目录下
        file = open(dropdir, 'wb')                     # 创建本地文件
        while True:
            data = sock.recv(1024)
            if not data: break
            file.write(data)                           # 储存数据
        sock.close()
        file.close()
        print('Client got ',filename, 'at', self.now())


def onSunbmit(content):                                #定义按钮的函数
    host = content['Server'].get()
    port = int(content['Port'].get())
    filename = content['File'].get()
    
    Client.client(Client(),host,port,filename)
    showinfo('Get-File','Download complete')

def main():                                            #利用tkinter设置GUI界面
    box = Tk()
    labels = ['Server', 'Port', 'File']
    rownum = 0
    content = {}

    for label in labels:
        Label(box, text=label).grid(column=0, row=rownum)
        entry = Entry(box)
        entry.grid(column=1, row=rownum, sticky=E + W)
        content[label] = entry
        rownum += 1
    box.columnconfigure(0, weight=0)
    box.columnconfigure(1, weight=1)
    Button(text='Submit', command=lambda :onSunbmit(content)).grid(row=rownum,column=0,columnspan=2)

    box.title('Get——File')
    box.bind('<Return>',(lambda event:onSunbmit(content)))
    mainloop()

main()

 

posted on 2017-09-29 17:21  啊峰哥  阅读(266)  评论(0编辑  收藏  举报

导航