Ron Halfon
Ron Halfon

Reputation: 105

Python - Client and server communication

I've written a python script that will communicate with a server, get its data and will send the data back to the server, some sort of an "echo client".

This is what I've written:

import socket
import time

def netcat(hostname, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.shutdown(socket.SHUT_WR)
    while 1:
        data = s.recv(1024)
        if data == "":
            break
        print "Received:", repr(data)
        data = data.replace("\n", "")
        time.sleep(1)
        s.sendall(data)
        print "Sent:", data
    print "Connection closed."
    s.close()

netcat("127.0.0.1", 4444)

I get this output:

Received: 'Welcome!\n'

And after that, I get this error:

Traceback (most recent call last):
  File "client.py", line 22, in <module>
    netcat("127.0.0.1", 4444)
  File "client.py", line 17, in netcat
    s.sendall(data)
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 32] Broken pipe

I've looked already for a solution for this error online, but with no luck.

Can someone please help me figure it out?

Thank you

Upvotes: 0

Views: 128

Answers (1)

Carl Von
Carl Von

Reputation: 178

I've been working on sockets a lot lately. I don't have a server right now to test your code so I thought I would quickly comment on what I see. You seem to be shutting down the socket (for writing) at the beginning, so your receive statement worked, but your sendall statement fails.

def netcat(hostname, port):
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((hostname, port))
    s.shutdown(socket.SHUT_WR) <-- WHY IS THIS HERE?

Upvotes: 1

Related Questions