[英]Receiving python json through sockets with java
我一直在遵循多個教程,通過套接字將Java代碼連接到python。
使用json數組,從Java發送到python效果很好。 但是,我似乎無法用Java接收東西。 我不太了解應該如何進行聆聽。 現在,我只是在15秒的while循環中進行監聽(python應該在收到輸入后立即發送),但是我感覺自己在做一些嚴重的錯誤。 也許有人有主意?
client.py:
import socket
import sys
import numpy as np
import json
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port
server_address = ('localhost', 10004)
print >>sys.stderr, 'starting up on %s port %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
def mysum(x):
return np.sum(x)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
infile = sock.makefile();
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
data = b''
while True:
new_data = connection.recv(16)
if new_data:
# connection.sendall(data)
data += new_data
else:
data += new_data[:]
print >>sys.stderr, 'no more data from', client_address
break
data= data.strip('\n');
print("data well received!: ")
print(data,)
print(np.array(json.loads(data)));
#send a new array back
sendArray = np.array( [ (1.5,2,3), (4,5,6) ] );
print("Preparing to send this:");
print(sendArray);
connection.send(json.dumps(sendArray.tolist()));
except Exception as e:
print(e)
connection.close()
print("closed");
finally:
# Clean up the connection
connection.close()
print("closed");
server.java:
import java.io.*;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import org.json.*;
import java.net.ServerSocket;
public class SocketTest {
public static void main(String[] args) throws IOException {
String hostName = "localhost";
int portNumber = 10004;
try (
//open a socket
Socket clientSocket = new Socket(hostName, portNumber);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
) {
System.out.println("Connected");
Double[][] test2 = new Double[5][2];
test2[1][1] = 0.1;
test2[1][0] = 0.2;
test2[2][1] = 0.2;
test2[2][0] = 0.2;
test2[3][1] = 0.1;
test2[3][0] = 0.2;
test2[4][1] = 0.2;
test2[4][0] = 0.2;
test2[0][1] = 0.2;
test2[0][0] = 0.2;
System.out.println("A");
out.println(new JSONArray(test2).toString());
System.out.println("B");
long t = System.currentTimeMillis();
long end = t + 15000;
while (System.currentTimeMillis() < end) {
String response;
while ((response = in.readLine()) != null) {
System.out.println("receiving");
System.out.println( response );
}
}
//listen for input continuously?
//clientSocket.close();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
python的輸出是:
data well received!:
('[[0.2,0.2],[0.2,0.1],[0.2,0.2],[0.2,0.1],[0.2,0.2]]',)
[[ 0.2 0.2]
[ 0.2 0.1]
[ 0.2 0.2]
[ 0.2 0.1]
[ 0.2 0.2]]
Preparing to send this:
[[ 1.5 2. 3. ]
[ 4. 5. 6. ]]
closed
waiting for a connection
connection from ('127.0.0.1', 40074)
來自Java的輸出:
A
B
問題是sendArray = np.array([(1.5,2,3),(4,5,6)]); 永遠不會被Java接收。 我覺得我缺少使聽的簡單方法了……感謝您的幫助。
發生這種情況是因為您的Java代碼被阻止。 看看B如何不打印到您的日志中? 那是因為由於這部分正在等待刷新命令,所以它不執行: out.println(new JSONArray(test2).toString());
。 您需要做的是out.flush();
如此下去。
您的代碼有多個問題。
1. Client.py和Server.java都在等待接收數據,這會導致死鎖。
當True時 ,Client.py被阻止,一直在等待新數據。
Server.java已發送長度為51的JSONArray(test2).toString() 。然后繼續在in.readLine()中等待。
請參見如何在java中識別InputStream的結尾 。 相同的想法適用於python。 最好知道要讀取多少個字節。
更改:因為JSONArray(test2).toString()的長度為51,所以您將其替換
while True:
new_data = connection.recv(16)
if new_data:
# connection.sendall(data)
data += new_data
else:
data += new_data[:]
print >>sys.stderr, 'no more data from', client_address
break
同
data = connection.recv(51)
2. Server.java調用in.readLine() 。 但是Client.py永遠不會發送'\\ n'並過早關閉套接字。 它導致in.readLine()拋出異常。
更改:發送'\\ n',以便Server.java可以成功讀取一行。
connection.send(json.dumps(sendArray.tolist()));
connection.send("\n");
3. Client.py關閉套接字,這將導致無限的in.readLine()引發“連接重置”異常。
更改:確保雙方不再發送/接收數據,然后合上插座。
1&2更改后的代碼。 (需要更多的精力來解決3,這不是這個問題的重點):
public class Server {
public static void main(String[] args) throws IOException {
String hostName = "localhost";
int portNumber = 10004;
try (
//open a socket
Socket clientSocket = new Socket(hostName, portNumber);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
) {
System.out.println("Connected");
Double[][] test2 = new Double[5][2];
test2[1][1] = 0.1;
test2[1][0] = 0.2;
test2[2][1] = 0.2;
test2[2][0] = 0.2;
test2[3][1] = 0.1;
test2[3][0] = 0.2;
test2[4][1] = 0.2;
test2[4][0] = 0.2;
test2[0][1] = 0.2;
test2[0][0] = 0.2;
System.out.println("A");
out.println(new JSONArray(test2).toString());
System.out.println("B");
long t = System.currentTimeMillis();
long end = t + 15000;
while (System.currentTimeMillis() < end) {
String response;
while ((response = in.readLine()) != null) {
System.out.println("receiving");
System.out.println( response );
}
}
//listen for input continuously?
//clientSocket.close();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Client.py輸出:
starting up on localhost port 10004
waiting for a connection
connection from ('127.0.0.1', 53388)
data well received!:
('[[0.2,0.2],[0.2,0.1],[0.2,0.2],[0.2,0.1],[0.2,0.2]]',)
[[ 0.2 0.2]
[ 0.2 0.1]
[ 0.2 0.2]
[ 0.2 0.1]
[ 0.2 0.2]]
Preparing to send this:
[[ 1.5 2. 3. ]
[ 4. 5. 6. ]]
closed
Server.java輸出:
Connected
A
B
receiving
[[1.5, 2.0, 3.0], [4.0, 5.0, 6.0]]
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.