socket programming

Pedro pedro at ncf.ca
Fri May 3 22:13:16 EDT 2013


I'm writing a simple app that uses socket programming, I'm using the following from tutorialspoint as a framework but I'm having a couple of issues implementing it. 

First - this code constantly loops around an open socket. Is there a way to use something like an interrupt so I don't have to loop constantly to monitor the socket?

Second, if any part of the program fails execution (crashes) the port often remains open on my windows machine and the only way to close it that i know of is through task manager or by rebooting the machine. Is there an easy way around this problem ? If I don't close the port the program can't open it again and crashes.

Thanks for looking



SERVER:

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
s.bind((host, port))        # Bind to the port

s.listen(5)                 # Now wait for client connection.
while True:
   c, addr = s.accept()     # Establish connection with client.
   print 'Got connection from', addr
   c.send('Thank you for connecting')
   c.close()                # Close the connection

CLIENT:
import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.

s.connect((host, port))
print s.recv(1024)
s.close                     # Close the socket when done



More information about the Python-list mailing list