与Python(服务器)通信的Java(客户端)

编程入门 行业动态 更新时间:2024-10-28 04:18:15
本文介绍了与Python(服务器)通信的Java(客户端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在做一个应该与Python Server通信的简单Java客户端应用程序。我可以轻松地将字符串发送到Python Server并在控制台中打印它,但是当我尝试在IF中使用接收到的字符串时,即使应该,也永远不会进入IF语句。

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.

这是Java客户端发送msg代码

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());

Python服务器代码:

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

因此,当我发送到 UP的Python服务器时,它应该发送回Java Client Works,但是我显示不起作用,并且在Python Server中输出数据是: UP

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"

为什么if语句不加入?

Why it isn't go into if statement?

推荐答案

DataOutputStream#writeUTF(...)的tputStream.html#writeUTF(java.lang.String) rel = nofollow> JavaDoc 说:

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

首先,将两个字节写入输出流,就像通过 writeShort方法给出输出的字节数一样

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

在python代码中,您的 data 值将以两个字节作为前缀要跟随的字符串。

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

更多推荐

与Python(服务器)通信的Java(客户端)

本文发布于:2023-08-07 03:30:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1316714.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:客户端   通信   服务器   Python   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!