我正在嘗試爲此腳本創建一個GUI。我想先按連接按鈕以連接到服務器。然後點擊發送發送文件。但是,當我按連接它發送一個空的文本文件和發送按鈕給我一個錯誤,我的套接字沒有定義。客戶端應用程序中的套接字未定義錯誤
from Tkinter import *
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.instruction = Label(self, text = 'Enter ip')
self.instruction.grid(row=0, column = 0, columnspan = 2, sticky = W)
self.instruction = Label(self, text = 'Enter Port')
self.instruction.grid(row=1, column = 0, columnspan = 2, sticky = W)
self.instruction = Label(self, text = ' ')
self.instruction.grid(row=2, column = 0, columnspan = 2, sticky = W)
self.instruction = Label(self, text = 'Enter path')
self.instruction.grid(row=5, column = 0, columnspan = 2, sticky = W)
self.ip = Entry(self)
self.ip.grid(row=0, column = 1, sticky = W)
self.port = Entry(self)
self.port.grid(row=1, column = 1, sticky = W)
self.path = Entry(self)
self.path.grid(row=5, column = 1, sticky = W)
self.submit_button = Button(self, text='connect', command = self.connect)
self.submit_button.grid(row = 1, column = 2, sticky = W)
self.send_button = Button(self, text='Send file', command = self.send)
self.send_button.grid(row = 5, column = 2, sticky = W)
self.text = Text(self, width = 80, height = 5, wrap = WORD)
self.text.grid(row = 10, column = 0, columnspan = 3, sticky = W)
def connect(self):
ip = self.ip.get()
port = int(self.port.get())
import socket
import sys
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
self.text.insert(0.0, 'connecting to' ,ip, port)
def send(self):
path = self.path.get()
f=open (path, "rb")
l = f.read(1024)
while (l):
s.send(l)
l = f.read(1024)
s.close()
root = Tk()
root.title("Client")
root.geometry("420x200")
app = Application(root)
root.mainloop()
這是我的服務器腳本
from Tkinter import *
import socket
import sys
class Application(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.text = Text(self, width = 35, height = 5, wrap = WORD)
self.text.grid(row = 0, column = 0, columnspan = 2, sticky = W)
self.submit_button = Button(self, text='start', command = self.start)
self.submit_button.grid(row = 2, column = 0, sticky = W)
def start(self):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.text.insert(0.0, 'Server started!\n')
self.s.bind(('',1080))
self.s.listen(10)
while True:
sc, address = self.s.accept()
i=1
f = open('file_'+ str(i)+".txt",'wb') #open in binary
i=i+1
while (True):
l = sc.recv(1024)
while (l):
print l
f.write(l)
f.flush()
l = sc.recv(1024)
f.close()
sc.close()
#s.close()
root = Tk()
root.title("Server")
root.geometry("500x250")
app = Application(root)
root.mainloop()
總是發佈實際的錯誤/追溯,如果你有任何。 – timss 2013-04-23 01:23:36
注意事項:除非你有充分理由不這樣做,否則應該將'import sys'和'import socket'放在模塊的頂部。 (實際上,你根本不應該有'import sys',因爲你從不使用它......) – abarnert 2013-04-23 01:41:37