Chris Aung
Chris Aung

Reputation: 9492

Python Socket (Simple server script)

I have this simple server script. My objective for this script is :

  1. Wait for a client connection
  2. Receive massages from client until the client disconnect
  3. Once client disconnect, wait for another client to connect
  4. Receive massages until the client disconnect
  5. Repeat...

import socket

server_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
server_socket.bind(("",5000))
server_socket.listen(5)
print "Awaiting Client connection"
client_socket, address =server_socket.accept()
print "Connection established.. with ",address
while True:
    data=client_socket.recv(512)
    if not data:
        client_socket.close()
        print "Client disconnected, Awaiting new connections..."
        client_socket, address =server_socket.accept()
        print "Connection from ",address
    else:
        print "RECIEVED:",data

My Question is even though the script seems to be working when i test it on a pair of pc, i noticed that after it received the connection from the client, that is line no 7

print "Connection established.. with ",address

the python shell window seems unresponsive (become not responding if i try to move the shell window) until the client send any message.

As far as i understand, if there is no incoming message from client, client_socket.recv(512) will just wait for the data from the client.

But why it became unresponsive? To make things clearer,

-the script works just fine ( it receive data and print it out from screen & wait for the new connection if client disconnect)

-the cursor in console windows stop blinking

-when i try to move the console window around , it become unresponsive and windows give me a message "this program has stopped responding"

Upvotes: 1

Views: 810

Answers (1)

Prahalad Deshpande
Prahalad Deshpande

Reputation: 4767

Basically, you script blocks on the accept call that is present after this line :

print "Client disconnected, Awaiting new connections..."

The accept call will return only when a particular client has attempted to connect to server. That is when your script will continue execution to the next line. This is the reason why you would see a message like This program is not responding in Windows.

You could consider the use of non-blocking socket I/O approach in order to ensure that your script is responsive.

Refer to this link for description of blocking and non-blocking calls. Also you can refer to this question to understand how to implement Non-blocking sockets in Python - and of course there are plenty of web resources too.

Hope this helps

Upvotes: 1

Related Questions