Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2011-09-10
7
Medium Priority
?
321 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 17

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 17

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 does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
LVL 17

Accepted Solution

by:
gelonida earned 2000 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

Tech or Treat!

Submit an article about your scariest tech experience—and the solution—and you’ll be automatically entered to win one of 4 fantastic tech gadgets.

Question has a verified solution.

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

In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
The Windows functions GetTickCount and timeGetTime retrieve the number of milliseconds since the system was started. However, the value is stored in a DWORD, which means that it wraps around to zero every 49.7 days. This article shows how to solve t…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
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)
Suggested Courses

609 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