我需要從 java 客戶端程式向 python 服務器程式發送訊息。
這是我的代碼:
Java客戶端:
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
// need host and port, we want to connect to the ServerSocket at port 7777
Socket socket = new Socket("localhost", 7777);
System.out.println("Connected!");
// get the output stream from the socket.
OutputStream outputStream = socket.getOutputStream();
// create a data output stream from the output stream so we can send data through it
DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
System.out.println("Sending string to the ServerSocket");
// write the message we want to send
dataOutputStream.writeUTF("Hello from the other side!");
dataOutputStream.flush(); // send the message
dataOutputStream.close(); // close the output stream when we're done.
System.out.println("Closing socket and terminating program.");
socket.close();
}
}
蟒蛇服務器:
from multiprocessing.connection import Listener
address = ('localhost',7777)
while True:
with Listener(address, authkey=None) as listener
with listener.accept() as conn:
print(conn.recv())
當我嘗試執行此操作時,在 Python 中出現以下錯誤:
OSError: got end of file during message
我究竟做錯了什么?
uj5u.com熱心網友回復:
在這種情況下,使用 multiprocessing 模塊似乎不合適,并且是問題的根本原因。這是一個簡化的 Python 服務器,它演示了如何實作您的目標。請注意,服務器在接受并處理任何單個連接后終止:
import socket
def server():
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('0.0.0.0', 7777))
s.listen()
conn, _ = s.accept()
with conn:
while (data := conn.recv(8192)):
print(data.decode())
if __name__ == '__main__':
server()
uj5u.com熱心網友回復:
這里的問題是多處理連接的 recv* 函式期望在訊息中獲得一個 32 位的前導碼,指示正在傳輸的實際資料量。所以這就是 Java 部分需要的樣子(我沒有擔心緩沖 IO - 只是保持簡單的骨骼):
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
String message = "Talking isn't doing. It is a kind of good deed to say well; and yet words are not deeds.";
try (Socket socket = new Socket("localhost", 7777)) {
try (DataOutputStream out = new DataOutputStream(socket.getOutputStream())) {
byte[] dts = message.getBytes();
out.writeInt(dts.length);
out.write(dts);
}
}
}
}
然后,您的 Python 服務器可能如下所示:
from multiprocessing.connection import Listener
def main():
listener = Listener(address=('0.0.0.0', 7777), family='AF_INET', authkey=None)
with listener.accept() as conn:
print(conn.recv_bytes().decode())
if __name__ == '__main__':
main()
因此,這意味著您的原始問題是由于 recv() 查看前 4 個位元組并將其解釋為傳入資料的長度。但這相當于比實際發送的要大得多的東西。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/360438.html
