How to make a TCP server work forever?

I have this code that I got from the docs:

#!/usr/bin/env python import socket TCP_IP = '192.168.1.66' TCP_PORT = 40000 BUFFER_SIZE = 20 # Normally 1024, but we want fast response s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(1) conn, addr = s.accept() print 'Connection address:', addr while True: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) conn.close() 

But it closes every time I turn off, how to make it work forever?

+6
source share
2 answers

you need to call accept() once for each connection you want to handle. in a first approximation:

 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((TCP_IP, TCP_PORT)) s.listen(1) while True: conn, addr = s.accept() print 'Connection address:', addr while True: data = conn.recv(BUFFER_SIZE) if not data: break print "received data:", data conn.send(data) conn.close() 
+4
source

Try changing the line

 if not data: break 

to

 if not data: continue 

thus, instead of exiting the loop, he will expect additional data

+6
source

Source: https://habr.com/ru/post/922153/


All Articles