简体   繁体   中英

Can't send message from python server to java client

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.

通常这是一个奇怪的设置,但是在服务器中,您应该在连接套接字(self.client)上发送,而不是在侦听套接字(self.socketPi)上发送。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM