簡體   English   中英

將數據從Java Socket Server發送到Python客戶端

[英]Send data from Java Socket Server to Python client

我也試圖從Java服務器和Python客戶端傳輸數據。 我可以成功地將數據從客戶端傳輸到服務器,但是根本沒有收到數據。

在python客戶端上,我有這個:(請注意,這是在單獨的線程中運行的)

#mp_log is a custom function for logging, treat it as a print.
def listen_loop():
global client_socket

mp_log("Client socket value:")
mp_log(repr(client_socket))

while True:
    mp_log("Waiting on data from the server. Inside while.")

    if client_socket is None:
        mp_log("Client Socket is null, skipping data check.")
        continue
    data = client_socket.recv(1)
    mp_log("Got some data: " + data)

如果此操作成功完成,則輸出將是客戶端套接字值,在服務器上等待,然后獲取一些數據。 但是,它一直在等待數據。

這意味着套接字顯然不是None,它正在等待接收緩沖區嗎? 我將接收緩沖區的大小設置為1,以查看是否有數據通過。 這是我從服務器發送的代碼:

// Earlier in the code, to create the writer. 
this.writer = new PrintWriter(this.socket.getOutputStream(),true);

我已啟用自動刷新功能作為測試,以確保實際刷新了數據。

public void send(String data) {
    System.out.println("Sending data to this client.");

    this.writer.println(data);
    this.writer.flush();
}

我知道由於控制台輸出出現而正在調用此方法。

我感到奇怪的是,我能夠從python客戶端發送數據,但沒有收到任何東西。 我嘗試過但失敗的其他事情是使用其他輸出方法,例如DataOutputStream。

編輯:添加用於兩種語言的套接字創建代碼。 Java的:

public Connection(Socket socket) throws IOException {
    this.socket = socket;
    this.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));

    this.writer = new PrintWriter(this.socket.getOutputStream(),true);

    this.listenThread = new Thread(this);
    this.listenThread.start();

    // Test message
    send("Test Message " + System.currentTimeMillis());
}

和Python:

global client_socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
threading.Thread(target=listen_loop).start()
client_socket.connect(("localhost", 5000))
 `data = client_socket.recv(1)`

嘗試通過data=client_socket.recv(1024)進行更改,我想我不確定是否有類似的問題,例如您給recv(1)的數字是您的緩沖區,希望能有所幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM