Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make my TCP server run forever?

I have this code 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 down each time I disconnect, how to I make it run for ever?

like image 957
Jason94 Avatar asked Aug 05 '12 10:08

Jason94


2 Answers

Try and change the line

if not data: break

to

if not data: continue

this way instead of exiting the loop, it will wait for more data

like image 160
j0N45 Avatar answered Sep 27 '22 17:09

j0N45


you need to call accept() once for each connection you wish to handle. to 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()
like image 40
SingleNegationElimination Avatar answered Sep 27 '22 17:09

SingleNegationElimination