我必須與服務器(我不能夠訪問服務器代碼),但傳輸協議(插座)連接是:Java的插座 - 服務器的響應總是空
(客戶端) - - >數據
ACK < - (服務器)
數據響應< - (服務器)(客戶端) - > ACK
假設服務器應該總是快速響應。我連接到服務器,我發送數據但響應爲NULL,如果我調試我的代碼,當我捕獲響應時發生異常: 「java.net.SocketException:軟件導致連接中止:recv失敗」
我的代碼:
public static void main(String[] args){
try{
String order = "datahere";
String responseServer;
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
outToServer.writeBytes(order);
responseServer = inFromServer.readLine();//exception if I try to debug my code
System.out.println("From server: " + responseServer); //responseServer is NULL
clientSocket.close();
} catch (IOException ex) {
System.out.println("Error: "+ex);
}
}
這是怎麼回事?任何想法?
我試圖禁用防火牆,並添加規則的端口9300,但結果是一樣的。
客戶給了我一個示例代碼中Vb.Net,它應該工作,我試圖複製它在Java中。
守則Vb.Net:
Dim message As String = "datahere";
Try
Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)
Dim client As New TcpClient(ip, port)
Dim stream As NetworkStream = client.GetStream()
stream.Write(data, 0, data.Length)
data = New [Byte](2048) {}
Dim responseData As [String] = [String].Empty
Dim bytes As Integer = stream.Read(data, 0, data.Length)
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes)
stream.Close()
client.Close()
Catch ex As Exception
End Try
SOLUTION:
Socket clientSocket = new Socket();
InetSocketAddress sa = new InetSocketAddress("XXX.XX.XX.XX", 9300);
clientSocket.connect(sa,500);
clientSocket.getOutputStream().write(order.getBytes("ASCII"));
byte[] data = new byte[2048];
int bytes = clientSocket.getInputStream().read(data, 0, data.length);
String responseData = new String(data, 0, bytes, "ASCII");
System.out.println("From server: " + responseData);
//Another way to catch the response:
//InputStreamReader in = new InputStreamReader(clientSocket.getInputStream());
//int data1 = in.read();
//while(data1 != -1) {
// System.out.print((char) data1);
// data1 = in.read();
//}
clientSocket.close();
'的System.out.println( 「從服務器:」 + responseServer);'總是返回'從服務器:null'? – messerbill
是的,「responseServer」始終爲NULL。我不能夠訪問服務器代碼,但服務器應始終應對這樣的問題一定是在我的代碼... – josekron
這意味着發送'datahere'服務器應該讓它回到你的數據? – messerbill