Socket connection- keeping it open until finished

In an echo server / client socket connection. How would you put the echo response in a loop so that the server / client doesn’t close the connection.

Socket Connection established.
Client: Send Data 1
Server: Receive Data 1 → Echo it back to the client.
Client: Send Data 2
Server: Receive Data 2 → Echo it back to the client.

Right now, with each new data set that is passed from the client to the server, it closes and creates a new socket… . I’m wanting to keep the client / server connection open and continue to echo back with no closure of the socket.

Brandon

python3

import socket

Create server socket.

serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM, proto=0)

Bind server socket to loopback network interface.

serv_sock.bind((‘127.0.0.1’, 6543))

Turn server socket into listening mode.

serv_sock.listen(10)

while True:
# Accept new connections in an infinite loop.
client_sock, client_addr = serv_sock.accept()
print(‘New connection from’, client_addr)

chunks = []
while True:
    # Keep reading while the client is writing.
    data = client_sock.recv(2048)
    if not data:
        # Client is done with sending.
        break
    chunks.append(data)

client_sock.sendall(b''.join(chunks))
client_sock.close()

Client side:

python3

import socket

Create client socket.

client_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

Connect to server (replace 127.0.0.1 with the real server IP).

client_sock.connect((‘127.0.0.1’, 6543))

Send some data to server.

client_sock.sendall(b’Hello, world’)
client_sock.shutdown(socket.SHUT_WR)

Receive some data back.

chunks =
while True:
data = client_sock.recv(2048)
if not data:
break
chunks.append(data)
print(‘Received’, repr(b’’.join(chunks)))

Disconnect from server.

client_sock.close()

[…]

Right now, with each new data set that is passed from the client
to the server, it closes and creates a new socket… . I’m wanting
to keep the client / server connection open and continue to echo
back with no closure of the socket.
[…]

Your code is explicitly calling the socket object’s close() method.
Stop doing that, and the socket won’t be closed until the script is
terminated.

The problem I have is on the second go around… first receive from client works, send to server works but when it come back to receiving from the client again I get:

IndexError: list index out of range

The only way I can make it work is by closing the socket, and then the client starts up a new socket. I want to keep the socket open for all back and forth communication between them. Any example code to do this?

Best,
Brandon

[…]

I want to keep the socket open for all back and forth
communication between them. Any example code to do this?

The Python documentation has a socket programming howto which covers
reusing an open socket:

https://docs.python.org/3/howto/sockets.html#using-a-socket

The short answer is that during a lull in communications, read block
(wait) until new data arrives. If you want the process to do other
things and just check the socket for new data periodically when it’s
not busy, see the section at the end on non-blocking sockets and the
select library.

If you are serious about asking for help, rather than just venting, then
please don’t just post the last line of the exception:

IndexError: list index out of range

Especially when it is so generic. All that tells us is that some
operation, somewhere in your code, or one of the libraries your code is
using, has tried to access an out-of-range index:

[10, 20, 30][9999]  # Out of range.

Why? How do you fix it? Is it a bug in a library you are calling, or a
bug in your code which you should fix? With so little information to go
by, we cannot guess.

So please post the full traceback, starting with the line “Traceback”.

That’s the bare minimum we need to suggest a fix.

1 Like