Solved

Problem with socket.socket and how do I fix it...

Posted on 2011-09-10
7
316 Views
Last Modified: 2012-06-27
working on a socket program.... the client side sends the information to the server side... all that works great my challenge is I want the two to exchange information when ever they make contact.... so I have one constantly listening and one constantly sending but they don't connect... if I start one then the other on start up it works perfectly but if they are both running and I try to connect the two nothing happens... why is this and how do I fix it ?



import wx
import threading 
from threading import Event, Thread
import thread
import socket
class Example(wx.Frame):
  
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(250, 200))
        panel=wx.Panel(self,-1) 
	wx.StaticText(panel, -1, 'sending',(0,0))
        self.Show()

class ThreadClass(threading.Thread):
    def run(self):
	
	host='197.168.1.195'
	#host=socket.gethostname()
	port = 51269
	size = 1000000
	addr = (host,port)
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	try:
	    f = open('duplicate_table2.txt', "r")
	    data = f.read()	    
	    f.close()
	    s.connect(addr)
	    s.send(data)
	    data = s.recv(size)
	    s.close()
	    print "Got it"
	    os.remove('duplicate_table2.txt')
	except socket.error:    
	    pass
	except IOError:
	    pass
	
ThreadClass().start() 
if __name__ == '__main__':
  
    app = wx.App()
    Example(None, title='Size')
    app.MainLoop()

Open in new window

import wx
import threading 
from threading import Event, Thread
import thread
import socket
class Example(wx.Frame):
  
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(250, 200))
        panel=wx.Panel(self,-1) 
	wx.StaticText(panel, -1, 'Recieve',(0,0))
        self.Show()


class ThreadClass(threading.Thread):
    def run(self):

        host = ''
	port = 51269
	backlog = 5
	size = 1000000
	addr = (socket.gethostname(), port)
	
	s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	s.bind((addr))
	s.listen(backlog)
	
	
	while 1:
	    
	    client, addr= s.accept()    
	    data = client.recv(size)
	    if data:
		client.send(data)		
		sqlite_file_to_write = open("recieved_dataII.txt", "ab"  )
		sqlite_file_to_write.write(data)    
		sqlite_file_to_write.close()
		
	    client.close()
	    
	
    
	    fname="recieved_dataII.txt"
	    f = open(fname, 'rb')    # notice the binary mode again
	    reader = csv.reader(f)
	    for row in reader:
		
		(Incident_number,Last_Name,First_Name,Age,Gender,Address,City,State,Zip,Ailment,Treatment,Patient_reprt,Initial_contact,Hospital, 
		Destination,Inservice,Provider_1,Provider_2,Sys,Dia,Pulse,Resp,Weather,Temp,Humid,Wind,TimeStamp,Refusal) =row
		
		Actual_Incident_number=None
		
		con = lite.connect('specialeventms2011a.sqlite')
		cur = con.cursor()
		cur.execute('insert into ptrecords values(?,?,?,?,?,?,?,?,?,?,?,?, ?, ?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
		    (Actual_Incident_number,Incident_number, Last_Name, First_Name, Age,Gender,Address,City,State,Zip
		     ,Ailment,Treatment,Patient_reprt,Initial_contact,Hospital,Destination,Inservice,
		     Provider_1,Provider_2,Sys,Dia,Pulse,Resp,Weather, Temp,Humid,Wind,TimeStamp,Refusal))
		con.commit()
		cur.close()
		con.close()
		
	    f.close()
	    os.remove('recieved_dataII.txt')
	    self.repopulate()
    def repopulate(self):	           
	InsertData.populate
    
ThreadClass().start() 

if __name__ == '__main__':
  
    app = wx.App()
    Example(None, title='Size')
    app.MainLoop(

Open in new window

)
0
Comment
Question by:dolamitejenkins
  • 4
  • 3
7 Comments
 
LVL 16

Expert Comment

by:gelonida
ID: 36518821
Hmm I don't really understand your question.

What do you mean with:

"but if they are both running and I try to connect the two nothing happens... "

You mean you start both applications on two different machines and only then you physicall
connect the cable????


0
 
LVL 16

Expert Comment

by:gelonida
ID: 36518827
Usually the server should be started first.

It will then listen on the all existing network interfaces for an incoming conection.

Then you should start your client.

If you don't know who starts fitst, then your client should try to connect.
If it fails it should wait a few seconds (depends on your application) and the rettry to connect.

I don't see any code in your client, that retries to connect. Perhaps this is your only problem:

I would add print statements to line 35 / 37 of your client.
I would add your client thread in a while loop and I would sleep for some time any time an error occured.

I hope this gives you some ideas.
0
 

Author Comment

by:dolamitejenkins
ID: 36518875
thanks ... that is exactly what my problem is... so if both machines have been running for a while and I connect them nothing happens they don't connect ... but if I let the server run then start and stop the client then they communicate and send and receive data
0
Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

 
LVL 16

Accepted Solution

by:
gelonida earned 500 total points
ID: 36519102
OK.

So try to add a while loop to your client and print statements in the exception section.
Attached  modified client code (untested) should give you some ideas.
import wx
import threading 
from threading import Event, Thread
import thread
import socket
class Example(wx.Frame):
  
    def __init__(self, parent, title):
        super(Example, self).__init__(parent, title=title, 
            size=(250, 200))
        panel=wx.Panel(self,-1) 
        wx.StaticText(panel, -1, 'sending',(0,0))
        self.Show()

class ThreadClass(threading.Thread):
    def run(self):
        while True:
            print "handle one connection attempt"
            success = self.run_once()
            if success:
               print "success"
               # do whatvever is appropriate
            else:
               print "fail"
               # do whatever is appropriate
               time.sleep(20) # adapt the delay 

    def run_once(self):        
        host='197.168.1.195'
        #host=socket.gethostname()
        port = 51269
        size = 1000000
        addr = (host,port)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        try:
            f = open('duplicate_table2.txt', "r")
            data = f.read()         
            f.close()
            s.connect(addr)
            s.send(data)
            data = s.recv(size)
            s.close()
            print "Got it"
            os.remove('duplicate_table2.txt')
            return True
        except socket.error:    
            print "socket error"
        except IOError:
            print "IOError"
        return False
        
ThreadClass().start() 
if __name__ == '__main__':
  
    app = wx.App()
    Example(None, title='Size')
    app.MainLoop()

Open in new window

0
 

Author Comment

by:dolamitejenkins
ID: 36519104
Thanks for the info ... I will keep you updated thanks
0
 

Author Comment

by:dolamitejenkins
ID: 36520610
Works great thanks
0
 

Author Closing Comment

by:dolamitejenkins
ID: 36520612
thanks works great
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to get all the API from website? 11 106
powershell md/mkdir/New-item   -Quiet 10 105
Powercli + List all VM's Per SCSILUN 15 91
Renaming with batch file 9 55
SSL is a very common protocol used these days when browsing the web.  The purpose is to provide security to communication, but how does it do it?  There are several pieces at work that have to be setup before SSL will even work and it requires both …
The purpose of this article is to demonstrate how we can upgrade Python from version 2.7.6 to Python 2.7.10 on the Linux Mint operating system. I am using an Oracle Virtual Box where I have installed Linux Mint operating system version 17.2. Once yo…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

820 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question