Communication Java(Client) with Python(Server)

筅森魡賤 提交于 2019-12-11 20:37:51

问题


I am doing a simple Java Client application which should communicate with Python Server. I can easily send a string to Python Server and print it in console, but when i'm trying to use received string in IFs it never get into IF statement even if it should.

Here is Java Client send msg code

        socket = new Socket(dstAddress, dstPort);
        dataOutputStream = new DataOutputStream(
            socket.getOutputStream());
        dataInputStream = new DataInputStream(socket.getInputStream());

        if(msgToServer != null){
            dataOutputStream.writeUTF("UP");
        }

        System.out.println(dataInputStream.readLine());

And Python Server code:

import socket

HOST = ''
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
print 'Socket now listening'

conn, addr = s.accept()
print 'Connected to: ' + addr[0] + ':' + str(addr[1])

data = conn.recv(1024)
if data == "UP":
     conn.sendall('Works')
else:
     conn.sendall('Does not work')
conn.close()
s.close()
print data

So when i send to Python Server "UP" it should send back to Java Client "Works", but i reveive "Does not work" and in Python Server the output data is: "UP"

Why it isn't go into if statement?


回答1:


The JavaDoc of DataOutputStream#writeUTF(...) says:

First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow

In you python code your data value will be prefixed with two bytes for the length of the string to follow.



来源:https://stackoverflow.com/questions/33654514/communication-javaclient-with-pythonserver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!