8
\$\begingroup\$

I put this together and am having some doubts to the number of connections I can make. I also doubt if I can brute force the server to serve up connections and then hang.

Please take a look and tell me what I can do better.

'''
    Simple socket server using threads
'''

import socket
import sys
from thread import *


HOST = '192.168.0.102'   # Symbolic name meaning all available interfaces
PORT = 8887 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
print 'Socket created'

#Bind socket to local host and port

try:
    s.bind((HOST, PORT))
except socket.error as msg:
    print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
    sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)

print 'Socket now listening'

#Function for handling connections. This will be used to create threads
def clientthread(conn):


    #infinite loop so that function do not terminate and thread do not end.
    while True: 


        #Receiving from client
        data = conn.recv(1024)
        print data

        reply = 'OK...' + data + str(addr)
        if not data:
            break

        conn.sendall(reply)

    #came out of loop
    conn.close()

#now keep talking with the client
while 1:
    #wait to accept a connection - blocking call
    conn, addr = s.accept()
    print 'Connected with ' + addr[0] + ':' + str(addr[1])

    #start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
    start_new_thread(clientthread ,(conn,))

s.close()
\$\endgroup\$
4
\$\begingroup\$

This code is very nice and easy to follow along with.


You should check the return value of socket.socket to make sure that the socket was created successfully


Usually, the name given to an error in a try/catch(or except) statement is something along the lines of "err", not "msg".


You should pass an error code to sys.exit so that external programs will know if there were any errors during the execution of the program.


In the while loop of clientthread, you use True to specify an infinite loop.

However, in the while loop just below that function, you use 1. You should stay consistent and use True for that one.


Instead of just printing the data, add a short message before it so the purpose of the number is more easily understood in output.

Example:

print 'Client data: ' + data

I don't believe that the s.close call at the end of your code will actually run.

This may not be necessary, as the socket may close automatically, but I would set up a signal handler to close the socket when someone tries to exit the program. You can use the signal library.

I came up with something like this:

def close_socket():
    s.close()
    sys.exit(0) # success

Then, right before your final while loop:

signal.signal(signal.SIGINT, close_socket)
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.