I am trying to make a GUI for this script I made. I want to press the connect button first to connect to the server. then hit send to send a file. But when I press connect it sends an empty text file and the send button gives me an error that my socket is not defined.
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()
this is my server script
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()