(在同一台机器上运行服务器和客户端,因此在客户端代码中使用 localhost)基本上我有这个程序所做的就是向客户端发送一个字符串,他稍后将转换为 json。但客户端部分的转换不是我的错误。当我从我的请求套接字继续执行 ObjectInputStreams (in) 和 ObjectOuputStreams(out) 时,它在客户端 (java) 上成功连接到我的服务器 (ruby)....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)
红宝石代码(服务器)
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代码(客户端)--->更新
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();
}
}
}