Solved

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

Posted on 2011-09-10
7
318 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 Is Transaction Monitoring and who needs it?

Synthetic Transaction Monitoring that you need for the day to day, which ensures your business website keeps running optimally, and that there is no downtime to impact your customer experience.

 
LVL 17

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

Microsoft Certification Exam 74-409

Veeam® is happy to provide the Microsoft community with a study guide prepared by MVP and MCT, Orin Thomas. This guide will take you through each of the exam objectives, helping you to prepare for and pass the examination.

Question has a verified solution.

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

Sequence is something that used to store data in it in very simple words. Let us just create a list first. To create a list first of all we need to give a name to our list which I have taken as “COURSE” followed by equals sign and finally enclosed …
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!
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…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

717 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