bsautner
bsautner

Reputation: 4822

python socket server with java client - socket.error: [Errno 32] Broken pipe

I'm trying to send commands to a rasberry pi using a python based socket server, where the server will get various string command, do something and then wait for the next command.

I have a socket server written in python running on a raspberry pi:

import socket

HOST = ''   # Symbolic name meaning the local host
PORT = 11113    # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
try:
    s.bind((HOST, PORT))
except socket.error , msg:
    print 'Bind failed. Error code: ' + str(msg[0]) + 'Error message: ' + msg[1]
    sys.exit()
print 'Socket bind complete'


    def listen():
        s.listen(1)
        print 'Socket now listening'

        # Accept the connection
        (conn, addr) = s.accept()
        print 'Server: got connection from client ' + addr[0] + ':' + str(addr[1])

        while 1:
            data = conn.recv(1024)
            tokens = data.split(' ', 1)
            command = tokens[0].strip()

            print command

            # Send reply
            conn.send("Ack")
            break

        conn.close()
        # s.close()
        listen()
        print "connection closed"

    listen()

Java Client:

public class Client {

    public static void main(String... args) throws Exception {
        int portNum = 11113;

        Socket socket;

        socket = new Socket("192.168.1.20", portNum);


        DataOutputStream dout=new DataOutputStream(socket.getOutputStream());
        dout.writeUTF("Hello");
        dout.flush();
        dout.close();
        socket.close();


    }
}

Python Server starts ok and waits for a connection, when I run the client code the server outputs the hello text followed by a lot of whitespace and then

edit: the white space is that while 1 loop outputing the incoming data and then looping out of control until it crashes. I want to output the text and keep listing for more connections.

edit 2: fixed python so it doesn't crash - i leave the loop and restart the listen process - which works. If this script can be improved please lmk - it doesn't look like it will scale.

Upvotes: 0

Views: 575

Answers (1)

jia hilegass
jia hilegass

Reputation: 503

errno.32 is: Broken pipe(the broken pipe error occurs if one end of the TCP socket closes connection(using disconnect) or gets killed and the other

In you java client, you send some data and close the socket right away which may cause the result.I am not familiar with java.But here is two things below you need to follow.

1.remove sock.close() in java client.

2.make your java client sleep for a while, but exit.

Upvotes: 1

Related Questions