0

I have written the following TCP client and server using python socket module. However, after I run them, no output is being given. It seems that the program is not able to come out of the while loop in the recv_all method Server:

import socket


def recv_all(sock):
    data = []
    while True:
        dat = sock.recv(18)
        if not dat:
            break
        data.append(dat)

    return "".join(data)


sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = '127.0.0.1'
PORT = 45678
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((HOST, PORT))
sock.listen(1)
print "listening at", sock.getsockname()
while True:
    s, addr = sock.accept()
    print "receiving from", addr
    final = recv_all(s)
    print "the client sent", final
    s.sendall("hello client")
    s.close()

Client :

import socket


def recv_all(sock):
    data=[]
    while True:
        dat=sock.recv(18)
        if not dat:
            break
        data.append(dat)
    return "".join(data)

sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
PORT=45678
HOST='127.0.0.1'
sock.connect((HOST,PORT))
sock.sendall("hi server")

final=recv_all(sock)

print "the server sent",final

1 Answers1

0

Because in server file you use an endless loop in another. I suggest you to edit recv_all method in both files this way:

def recv_all(sock):
data = []
dat = sock.recv(18)
data.append(dat)
return "".join(data)

But after edit like this your server stays on until KeyInterrupt, while you should run client file everytime you want to send data. If you want an automatically send/receive between server and client, I offer you try threading.

Shojajou
  • 195
  • 6
  • 15