Can't send message from python server to java client

时间:2015-07-08 15:42:49

标签: java python sockets server

I try to create a client/server application between my Raspberry Pi (server in Python) and a java Client over my local network.

I can't figure out how to send message from the Python server to the Java client. I always have the error : [Errno 32] Broken pipe.

I can't seen where I'm wrong.

Here the Server code :

class ServerLED():
'''
classdocs
'''


def __init__(self, port = 15555):
    '''
    Constructor
    '''
    self.socketPi = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socketPi.bind(("", port))
    self.response = ""

def listening(self):
    self.socketPi.listen(5)
    self.client, self.address = self.socketPi.accept()
    print "{} connected".format( self.address )

def receivingMessage(self):
    self.response = self.client.recv(1024)
    if self.response != "":
            print self.response

def answer(self):
    messageTosend = "Echo \r\n"
    try:
        self.socketPi.send(messageTosend)
    except socket.error, e:
        print "error is ", e
        self.socketPi.close()

I use the function this way :

socketPi = Server.ServerLED()
print "listening..."
socketPi.listening()
print "sending message..."
socketPi.answer()
print "done"
socketPi.receivingMessage()

On the client side (in JAVA) :

Socket socket = new Socket("192.168.1.18", 15555);
System.out.println("SOCKET = " + socket);

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
str = in.readLine();      // Reding "ECHO"

System.out.println(str);     

out.println("Hello");          // sending message

I'm always stuck in the first "send()" of the server. If I start by sending a message from the client to the server, the server reads it but fails to respond.

Server output :

Start python for LED
listening...
('192.168.1.13', 58774) connected
sending message...
error is  [Errno 32] Broken pipe

Does someone know where I am wrong ? Thanks a lot.

Maxime.

2 个答案:

答案 0 :(得分:6)

It is a strange setup generally, but in the server you should be sending on the connection socket (self.client), not on the listening socket (self.socketPi).

答案 1 :(得分:0)

One problem is that the Socket you create in java isn't bind, that is - the Socket object is just created, but not opened waiting for the raspberry pi incoming socket connection.

Add the row

socket.bind(new java.net.InetSocketAddress("192.168.1.18", 15555));

after the socket is created. The address in the Socket constructor is probably not nescessary.