(運行服務器和同一臺計算機上的客戶端,因此本地主機是在客戶端代碼中使用) 基本上我有這個程序做什麼是發送一個字符串到客戶端,他將後來轉換爲json。但客戶端部分的轉換不是我的錯誤。它在客戶端(Java)後,我成功地連接到我的服務器(紅寶石)時,我從我的請求套接字進行ObjectInputStreams()和ObjectOuputStreams(出).... 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代碼(服務器)
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();
}
}
}
我不知道Java的那麼好,但對我來說,似乎您使用的是Java'ObjectStream'元讀取從插座普通字符串。我會認爲一個Java ObjectStream只能與另一個ObjectStream進行通信。即你只能在這樣的流內傳遞Java對象。一個普通的Ruby字符串不是一個Java對象,所以代碼永遠不會像這樣互操作。你也需要在Java端閱讀純字符串,而不是'ObjectStream'。 – Casper
基本上在Java端調用'requestSocket.read()'(我猜是因爲我不是Java大師)。跳過所有'流'的東西。 – Casper
再次,閱讀是沒有問題的,我在這種情況下,因爲我還沒有得到通過requestSocket.getInputStream()部分... – richddr