0

I'm using a simple tcp_server in python. Here is the code:-

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

conn, addr = s.accept()
#inputs = [conn, serial_obj]
outputs = []
#read_input.read_input(inputs,outputs)
while 1:
    data = conn.recv(BUFFER_SIZE)
    if not data: break
    print "received data:", data
    conn.send(data)

conn.close()

My question is once it receives the data, the connection is dropped and I have to re-run the tcp_server program to initiate the connection. How do I keep it listening forever.

Praful Bagai
  • 16,684
  • 50
  • 136
  • 267
  • 3
    You never accept a new connection. You accept one connection, then read from it. – Jakob Bowyer Jul 27 '14 at 04:41
  • Sorry, I mean when I receive the data, the connection is dropped. TO again receive the data from the same connection, I have to restart the program. How can I make it listen foreover. THanks – Praful Bagai Jul 27 '14 at 04:42
  • You will recv every 1024 bytes. – Jakob Bowyer Jul 27 '14 at 04:48
  • Ok. Point taken. But what if I want to keep receiving 1024 bytes again and again. – Praful Bagai Jul 27 '14 at 04:50
  • Your code, as written, will receive as many chunks (up to 1024 bytes each) as you send it on one connection, but it will only ever accept one connection. From your comments, it appears that your client code only sends one chunk per connection attempt. Can you include a client program so that we can advise you on your system as a whole? – Robᵩ Jul 27 '14 at 04:54

1 Answers1

1

You need two nested while loops. The outer loop runs forever, once per incoming connection. The inner loop runs according to the data it receives on the current connection. Try this:

import socket

TCP_IP = '127.0.0.1'
TCP_PORT = 5005
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)

while True:
    conn, addr = s.accept()
    #inputs = [conn, serial_obj]
    outputs = []
    #read_input.read_input(inputs,outputs)
    while 1:
        data = conn.recv(BUFFER_SIZE)
        if not data: break
        print "received data:", data
        conn.send(data)
    conn.close()
Robᵩ
  • 163,533
  • 20
  • 239
  • 308