(在同一台机器上运行服务器和客户端,因此在客户端代码中使用localhost) 基本上我有这个程序做的是向客户端发送一个字符串,他稍后将转换为json。但客户端部分的转换不是我的错误。我从客户端(java)成功连接到我的服务器(ruby)后,我从我的请求套接字继续ObjectInputStreams(in)和ObjectOuputStreams(out).... out = requestSocket.getOutputStream()工作正常但是in = requesSocket.getInputStream()给了我一个IOException ..我已经尝试了一切,但我无法解决这个任何帮助表示赞赏。 PD:这不是一个硬件,只是我想要学习不同语言之间的互动。
这是客户端的错误:
java.net.SocketException: Software caused connection abort: recv failed
at java.net.SocketInputStream.socketRead0(Native Method)
at java.net.SocketInputStream.read(Unknown Source)
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
RUBY CODE(服务器)
require 'rubygems'
require 'socket'
require 'json'
jsonString = '{"test":23, "prueba":1234}'
serverB = TCPServer.new(2000)
loop{#server runs forever
Thread.start(serverB.accept) do |client|
client.write(jsonString)
client.close #disconnect from the client
end
}
JAVA CODE(客户端)--->更新
import java.io.*;
import java.net.*;
import org.json.simple.*;
public class json
{
public static void main(String[] args) throws InterruptedException, ClassNotFoundException
{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
try {
//creating a socket to connect to the server
requestSocket = new Socket("localhost",2000);
//Get input and output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
//THIS WORKS NOW
BufferedReader in = new BufferedReader(new InputStreamReader(requestSocket.getInputStream()));
//THIS IS WHERE IT FAILS NOW
String jsonString = in.readLine();
String msg = JSONValue.toJSONString(jsonString);
//Convert string to JSON format and print something
Object obj = JSONValue.parse(msg);
JSONObject jobj = (JSONObject)obj;
System.out.print(jobj.get("test"));
try {
in.close();
out.close();
requestSocket.close();
} catch (Exception e2) {
e2.printStackTrace();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
我测试了您的代码,但您仍遇到运行ObjectOutputStream
的问题。注释掉这两行(以out.flush()
结尾的行)。
此外,您现在正在呼叫readLine()
,这意味着BufferedReader
正在等待一条线路。一行以"\r\n"
结尾。
所以解决方法是将其添加到Ruby代码中:
Thread.start(serverB.accept) do |client|
client.write(jsonString)
client.write("\r\n")
client.close
end
运行它就像它适用于我(Linux Ubuntu)。
答案 1 :(得分:0)
您不能使用ObjectInputStream来读取JSON字符串,您必须将其作为字符串读取,然后使用json包将其转换为对象。
ObjectInputStream用于读取二进制序列化的java对象,它与json无关。