我是Java的新手(基本上不得不爲此項目動態學習它),但我試圖發送一個XML命令到服務器(一個傳感器在我的實驗室)從它獲得一些數據。爲此,我編寫了一個Java程序,並從命令行運行它。連接建立成功,並且(我認爲)該消息正在成功發送 - 但它正陷入「等待響應」。沒有收到迴應通過TCP/IP使用Java發送XML
這裏是我的Java代碼以供參考。我從客戶端/服務器TCP教程中獲得了大部分內容,並相應地調整了IP,端口和外發消息。再次,我對此很陌生,所以任何幫助表示讚賞。
// Java Socket Example - Client
import java.io.IOException; // Throws exception if there is an issue with input or output
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress; // This class represents an Internet Protocol address
import java.net.Socket;
import java.net.UnknownHostException;
/**
* This class implements java socket Client
*/
public class SocketClientExample {
\t public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException {
\t \t // get the localhostIP address, if server is running on some other IP, use that
\t \t System.out.println("Attempting connection to GE Reuter Stokes");
\t \t InetAddress host = InetAddress.getByName("10.212.160.4"); // IP GOES HERE
\t \t Socket socket = null; // start out as null, protocal
\t \t ObjectOutputStream oos = null; // This will change, just setting default
\t \t ObjectInputStream ois = null;
\t \t // establish the socket connection to the server
\t \t socket = new Socket("10.212.160.4", 3010); // 9876 is just the port number
\t \t System.out.println("Made it past Socket Initialization");
\t \t // write to socket using ObjectOutputStream
\t \t oos = new ObjectOutputStream(socket.getOutputStream()); // new instance of OOS that will write to the socket
\t \t System.out.println("Sending request to Socket Server");
\t \t // Initializing request string
\t \t String request = new String("0xF00041 " + "<Discovery><CommChannelName>Unknown</CommChannelName></Discovery>");
\t \t // In our version, this is where the XML script would go
\t \t oos.writeObject(request);
\t \t System.out.println("Request was sent. Awaiting response.");
\t \t // read the server response message
\t \t ois = new ObjectInputStream(socket.getInputStream());
\t \t // convert the response into a string
\t \t String message = (String) ois.readObject();
\t \t System.out.println("Message: " + message);
\t \t // close your resources
\t \t ois.close();
\t \t oos.close();
\t \t Thread.sleep(100);
\t }
}
這是極有可能的東西與傳感器多 - 但我想它不會傷害到對碼的第二雙眼睛。
排除服務器側:
嘗試更多的東西這樣代替(假定傳感器發送回以類似的報頭+ XML格式作爲對該請求的響應)。爲此創建一個測試服務器,輸出它獲取的數據和其他相關的調試消息。用結果編輯這個問題。爲此使用'ServerSocket'。 Google瞭解ServerSocket文檔。在創建一個新的ServerSocket之後,接受一個與'Socket client = server.accept();'的連接,然後從該客戶端的輸出流中讀入數據,打印出來並回復。 – Aaron
'ObjectOutputStream'和'ObjectInputStream'不是在這種情況下使用的正確類型的流,當然不是'writeObject()'和'readObject()'方法。你應該使用'OutputStreamWriter'(在其上有一個'BufferedWriter')或'DataOutputStream'和'InputStreamReader'(在它上面有一個'BufferedReader')。 –
另外,0xF00041應該代表什麼?你確實意識到你將它作爲一個8字符的字符串發送,而不是3-4字節的整數,不是嗎?傳感器實際上期望您發送什麼?你能提供一些協議文件嗎? –