Solved

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

Posted on 2011-09-10
7
312 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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Article by: Swadhin
Introduction of Lists in Python: There are six built-in types of sequences. Lists and tuples are the most common one. In this article we will see how to use Lists in python and how we can utilize it while doing our own program. In general we can al…
Configuring network clients can be a chore, especially if there are a large number of them or a lot of itinerant users.  DHCP dynamically manages this process, much to the relief of users and administrators alike!
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

706 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now