我需要使用Java编写程序来连接套接字,发送验证数据并接收答案。我在Python中有一个可以正常工作的代码,我以此为例。
我可以连接,但是发送数据后我什么也没收到。
在我编写的Java代码下面:
String hostname = "remoteHost";
int port = 4200;
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
JSONObject json = new JSONObject();
JSONObject params = new JSONObject();
params.put("code", "authCode");
json.put("jsonrpc", "2.0");
json.put("method", "authenticate");
json.put("params", params);
json.put("id", "0");
out.write(json.toString());
System.out.println(in.readLine());
以下是Pyhton中的示例:
import socket, json
from dateutil import parser
host = "app.sensemetrics.com"
port = 4200
apiCode = "YourAPIKey"
# Open a new socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
# Send the authentication request
handshake = json.dumps({
"jsonrpc": "2.0",
"method": "authenticate",
"params": {
"code" : apiCode
},
"id": 0
})
s.send(handshake)
# Parse the response
jsonFrame = decodeOneJsonFrame(s)
response = json.loads(jsonFrame)
print("\r\nHandshake Exchange:\r\n" + " --> " + handshake + "\r\n" + " <-- " + jsonFrame)
# Close the socket connection
s.close()
答案 0 :(得分:1)
out.write(json.toString());
我认为您也应该致电out.flush()
。
写完回复后,别忘了也拨打另一端的flush
,这样您就可以用System.out.println(in.readLine());
来阅读
请参见here