[Tutor] Questions Regarding Sockets

Alan Gauld alan.gauld at btinternet.com
Sat Apr 14 19:32:15 CEST 2012

On 14/04/12 17:41, Khalid Al-Ghamdi wrote:

> 1- In line (15), what are these variables tcpCliSock,addr supposed to
> hold and do?

The socket object and the IP address of the client that is connecting to 
the server. When a client connects to a server the server assigns a new 
temporary socket connection that the client  uses. Each connection gets 
a new temporary socket assignment. What happens to the old one is 
implementation dependent and you should not try to reuse it.

> 2- Why do I have to specify the buffer size and what does it mean?

A buffer is an area of memory used as a kind of holding bay into which 
data is put, usually temporarily. You need to specify where the incoming 
data will go and how much space you expect to use.

> 3- When I try to run the below code and its corresponding client it
> works ok for the first time, but then it gives me this error:
> Traceback (most recent call last):
>    File "C:\Python32\Khalid Stuff\tsTserv3.py", line 12, in <module>
>      tcpSerSock.bind(ADDR)
> socket.error: [Errno 10048] Only one usage of each socket address
> (protocol/network address/port) is normally permitted
> I thought it had to do with  the address so I changed the port and it
> worked ok. so,:
> A/ isn't the optional tcpSerSock.close() supposed to close the
> connection for later reuse?

Yes, but there is sometimes a delay before the OS cleans up, it may be 
that which you are seeing.

> B/ why is it when i go to the IDLE and enter tcpSerSock.close() and it
> accepts it, it still gives the same error and doesn't close the
> connection for reuse by my code?

It may be an OS level thing. But I'm by no means an expert on the OS 
networking layers! Which OS are you running under?

>       HOST = ''
>       PORT = 21567
>       BUFSIZ = 1024
>       ADDR =(HOST, PORT)
>       tcpSerSock = socket(AF_INET, SOCK_STREAM)
>       tcpSerSock.bind(ADDR)
>       tcpSerSock.listen(5)
>       while True:
>            print('waiting for connection ...')
>            tcpCliSock, addr = tcpSerSock.accept()
>            print('...connected from: ', addr)
>            while True:
>                data = tcpCliSock.recv(BUFSIZ)
>                if not data:
>                     break
>            tcpCliSock.send(bytes('[{}]
>                            {}'.format(ctime(),data.decode('utf-8')),'utf-8'))
>            tcpCliSock.close()
>       tcpSerSock.close()

I can't help but think you should check if there actually is a 
connection before starting the second loop... What do you expect
if the accept() fails to find anything?

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list