Thread: python socket recv never works properly help
i've been writing server , guit client try , file transfer , network commucation working. recv command nerver works properly. times ill send("simple line") , output reclieve "simple line" other times have load of other info on end of
example want connect server , server lists songs available download
looked throught files , sent each file name 1 send command
used loop recv , print each send command expecting 1 filename per line
instead got 1024 bit blocks of text leftover bits of earlier filenames despite not sending them in send command.
messed around hours , hours , still cant working. here example of functions have , outputs debugging
serv.py
cli.pycode:if(commands[0] == 'list'): whatpacketshouldlooklike="" print "[request] list files ", address fil = list_files(path) f in fil: sdata = f whatpacketshouldlooklike += sdata + "-eos-" newsock.send(sdata +"-eos-") #print "sent: " + sdata newsock.send("\r\n\r\neof") whatpacketshouldlooklike += "\r\n\r\neof" print "---------------------------------" print whatpacketshouldlooklike print "---------------------------------"
the 2 problems code. works , lists files, lists 1 file.code:def get_data(self,size = 1024): self.alldata = "" while 1: while gtk.events_pending(): gtk.main_iteration() self.recvdata = self.s.recv(size) self.alldata += self.recvdata if self.alldata.find("\r\n\r\neof"): print "recieved end message" self.rdata = self.alldata[:self.alldata.find("\r\n\r\neof")] break print "all data recieved: " + str(len(self.rdata)) + "bytes" print "all data :\n" + self.rdata + "\n-------------------------------------------------" self.infiles = self.rdata.split("-eos-") nf in self.infiles: if len(nf) > 2: self.add_message(self.incomingicon,nf)
second problem once press button send 1 command, if works , proper response, when type new command , press button again 100% of time gui application freezes. dont know why. full codes
code:#!/usr/bin/python import os, glob, shutil import sys import socket import time import string import configparser #functions def sendfile(socket,path,name): confirm = socket.recv(1024) if(confirm == "_begin_"): #get file size siz = os.path.getsize(path + name) socket.send("_f_siz_=" + str(siz)) fullfile = path + name print "[notice] sending file " + fullfile if os.path.exists(fullfile): #file exists can transfer it. #open file in rb #loop through , send socket f = file(fullfile,'rb') while true: data = f.read(1024) if len(data) <= 0: socket.send(data) break socket.send(data) f.close() print "[notice] finished sending file " + fullfile else: print "no confirmation recieved" def list_files(path): os.chdir(path) ffiles = glob.glob("*.*") return ffiles; def usage(): print "usage: filerec.py [portnumber][base address read from]" #usage: filerec.py [portnumber][base address read from] #check argv if(len(sys.argv) > 2): #we have @ least 3 args can contunue port = int(sys.argv[1]) path = sys.argv[2] if os.path.isdir(path): #path valid print "server listening - serving files " + path # lets create socket sock = socket.socket(socket.af_inet, socket.sock_stream) sock.bind(('', port)) sock.listen(5) #loop accept connections. while true: sdata = "" newsock, address = sock.accept() print "**connection ", address rcvdata = newsock.recv(1024) commands = rcvdata.split(' ') if(commands[0] == 'list'): whatpacketshouldlooklike="" print "[request] list files ", address fil = list_files(path) f in fil: sdata = f whatpacketshouldlooklike += sdata + "-eos-" newsock.send(sdata +"-eos-") #print "sent: " + sdata newsock.send("\r\n\r\neof") whatpacketshouldlooklike += "\r\n\r\neof" print "---------------------------------" print whatpacketshouldlooklike print "---------------------------------" elif(commands[0] == 'get'): #remove first word filenam = " ".join(commands[1:]) print "**requested download of " + filenam if(os.path.exists(path + filenam)): newsock.send("_yesfile_") sendfile(newsock,path,filenam) else: print "file not exist" + path + filenam newsock.send("_nofile_") elif(commands[0] == 'quit'): newsock.close() sock.close() print "**remote host terminated connection" break; else: print "**invalid command " + rcvdata newsock.send("invalid command \r\n\r\neof") else: print "invalid path " + path exit() else: usage()
code:#!/usr/bin/env python #imports import os import sys import gtk import glob import string import pygtk import socket import shutil pygtk.require('2.0') class base: stoplistening = false def sendcommand(self,widget): command = self.commandbartxtbox.get_text() if command.lower() == "quit": self.stoplistening = true self.s.close() self.add_message(self.erroricon, "closed connection server") elif command.lower() == "list": self.send_data(command) self.get_data(1024) else: self.send_data(command) self.get_data(1024) def send_data(self, data): #try put size try: self.s.send(data) self.add_message(self.outgoingicon,data) except: self.add_message(self.erroricon,"message not sent") def get_data(self,size = 1024): self.alldata = "" while 1: while gtk.events_pending(): gtk.main_iteration() self.recvdata = self.s.recv(size) self.alldata += self.recvdata if self.alldata.find("\r\n\r\neof"): print "recieved end message" self.rdata = self.alldata[:self.alldata.find("\r\n\r\neof")] break print "all data recieved: " + str(len(self.rdata)) + "bytes" print "all data :\n" + self.rdata + "\n-------------------------------------------------" self.infiles = self.rdata.split("-eos-") nf in self.infiles: if len(nf) > 2: self.add_message(self.incomingicon,nf) #self.add_message(self.erroricon,"error reading host.") def treeview_changed(self,widget,event,data=none): adj = self.contentwindow.get_vadjustment() adj.set_value(adj.upper - adj.page_size) def add_message(self,pix,txt): self.liststore.append([pix,txt]) def connect_to_host(self,widget): self.ip = self.connectbariptxtbox.get_text() self.port = self.connectbarporttxtbox.get_text() try: self.s.connect((self.ip, int(self.port))) self.add_message(self.successicon,"successfully connected host") except: self.add_message(self.erroricon,"error connection host: " + self.ip + " on port" + self.port ) def destroy(self,widget,data=none): gtk.main_quit() def set_images(self): self.currentdir = os.getcwd() + "/icons/" self.incomingicon = gtk.gdk.pixbuf_new_from_file_at_size(self.currentdir + "recv.png",24,24) self.outgoingicon = gtk.gdk.pixbuf_new_from_file_at_size(self.currentdir + "sent.png",24,24) self.erroricon = gtk.gdk.pixbuf_new_from_file_at_size(self.currentdir + "error.png",24,24) self.successicon = gtk.gdk.pixbuf_new_from_file_at_size(self.currentdir + "success.png",24,24) def __init__(self): #lets window self.window = gtk.window(gtk.window_toplevel) self.window.set_position(gtk.win_pos_center) self.window.set_size_request(800,800) self.window.set_title("remote file downloader") #connectbar hbox #label ip txtbox label port button connect self.connectbar = gtk.hbox() self.connectbar.set_size_request(800,30) #declare connectbar widgets self.connectbariplabel = gtk.label(" ip:") self.connectbariptxtbox = gtk.entry() self.connectbariptxtbox.set_text("brian-movie-downloads") self.connectbariptxtbox.set_size_request(500,30) self.connectbarportlabel = gtk.label("port:") self.connectbarporttxtbox = gtk.entry() self.connectbarporttxtbox.set_size_request(60,30) self.connectbarconnectbutton = gtk.button("connect") self.connectbarconnectbutton.connect("clicked",self.connect_to_host) #pack them bar self.connectbar.pack_start(self.connectbariplabel,false,false,5) self.connectbar.pack_start(self.connectbariptxtbox,false,false,5) self.connectbar.pack_start(self.connectbarportlabel,false,false,5) self.connectbar.pack_start(self.connectbarporttxtbox,false,false,5) self.connectbar.pack_start(self.connectbarconnectbutton,false,false,5) #scroll window hbar treeview , listview need declared before self.contenthbar = gtk.hbox() self.contenthbar.set_size_request(800,700) #liststore creation self.liststore = gtk.liststore(gtk.gdk.pixbuf,str) #treeview self.treeview = gtk.treeview(self.liststore) self.treeview.connect('size-allocate', self.treeview_changed) #self.treeview.connect("row-activated", self.on_src_activated) #self.treeview.set_rules_hint(true) #columns , cell rendering self.imgrend = gtk.cellrendererpixbuf() self.txtrend = gtk.cellrenderertext() #columns self.imgcolumn = gtk.treeviewcolumn(" action ", self.imgrend, pixbuf = 0) self.imgcolumn.set_min_width(70) self.txtcolumn = gtk.treeviewcolumn(" data", self.txtrend, text = 1) self.txtcolumn.set_min_width(650) ##add columns self.treeview.append_column(self.imgcolumn) self.treeview.append_column(self.txtcolumn) self.contentwindow = gtk.scrolledwindow() self.contentwindow.set_shadow_type(gtk.shadow_etched_in) self.contentwindow.set_policy(gtk.policy_automatic, gtk.policy_automatic) self.contentwindow.add(self.treeview) self.contenthbar.pack_start(self.contentwindow) #delcare command hbox self.commandbar = gtk.hbox() self.commandbar.set_size_request(800,30) #declare commandbar txtbox , button self.commandbarsendbutton = gtk.button("send") self.commandbarsendbutton.connect("clicked",self.sendcommand) self.commandbartxtbox = gtk.entry() self.commandbartxtbox.set_size_request(500,30) self.commandbar.pack_start(self.commandbartxtbox,false,false,5) self.commandbar.pack_start(self.commandbarsendbutton,false,false,5) #declare vertical bar self.mainbar = gtk.vbox() self.mainbar.pack_start(self.connectbar,false,false,5) self.mainbar.pack_start(self.contenthbar,false,false,0) self.mainbar.pack_start(self.commandbar,false,false,5) #other functions run before displaying window self.set_images() self.s = socket.socket(socket.af_inet, socket.sock_stream) #self.add_message(self.successicon,"its working! huzzah!!") #add windown , display self.window.add(self.mainbar) self.window.show_all() self.window.connect("destroy",self.destroy) def main(self): gtk.main() if __name__ == "__main__": base = base() base.main()
please help, ive been working on ages. if run code on machine , send me editing code, feel ive tried every solution google , non work me.
want happen
enter ip , port , press connect
connects ip , port (that works fine)
when type in command , press send
i.e list - gets list of files in remote drive , prints them each in new row
doesnt grey out when go send second command
i have couple questions:
1. said there multiple possible outcomes, repeatable? (if run client program twice , request list multiple times each run, 1st, 2nd, etc. request have same outcome?)
2. can try writing simpler command first, "hello" server respond simple message? easier figure out mistakes on simpler problems before diving more complex routine
not going go through , errors right away, because wouldn't teach anything. rather guide through.
Forum The Ubuntu Forum Community Ubuntu Specialised Support Development & Programming Programming Talk python socket recv never works properly help
Ubuntu
Comments
Post a Comment