Solved

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

Posted on 2011-09-10
7
313 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
Give your grad a cloud of their own!

With up to 8TB of storage, give your favorite graduate their own personal cloud to centralize all their photos, videos and music in one safe place. They can save, sync and share all their stuff, and automatic photo backup helps free up space on their smartphone and tablet.

 
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

Save on storage to protect fatherhood memories

You're the dad who has everything. This Father's Day, make sure your family memories are protected. My Passport Ultra has automatic backup and password protection to keep your cherished photos and videos safe. With up to 3TB, you have plenty of room to hold the adventures ahead.

Question has a verified solution.

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

Suggested Solutions

Please see preceding article here: http://www.experts-exchange.com/Networking/Operating_Systems/A_11209-Root-Bridge-Election.html Figure 1 After Root Bridge has been elected, then what?..... Let's start by defining a Root Port in la…
We recently endured a series of broadcast storms that caused our ISP to shut us down for brief periods of time. After going through a multitude of tests, we determined that the issue was related to Intel NIC drivers on some new HP desktop computers …
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
After creating this article (http://www.experts-exchange.com/articles/23699/Setup-Mikrotik-routers-with-OSPF.html), I decided to make a video (no audio) to show you how to configure the routers and run some trace routes and pings between the 7 sites…

863 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

21 Experts available now in Live!

Get 1:1 Help Now