2016-08-04 1 views
0

저는 Java에 익숙하지 않습니다. (기본적으로이 프로젝트에서이 기능을 익혀야합니다.)하지만 서버에 XML 명령을 보내려고합니다. 내 실험실에서) 일부 데이터를 얻을 수 있습니다. 이를 위해 자바 프로그램을 작성했으며 커맨드 라인에서 실행하고 있습니다. 연결이 성공적으로 이루어지며 메시지가 성공적으로 전송되고 있습니다. 그러나 응답이 대기 중입니다.자바를 사용하여 TCP/IP를 통해 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 } 
 
}

그것은 센서 가능성이 뭔가 것보다 더

는 -하지만이 코드에 눈의 두 번째 세트를 해치지 않을 것이라고 생각.

+0

규칙을 서버 측을 제. 이를위한 테스트 서버를 생성하고 얻은 데이터 및 기타 관련 디버그 메시지를 출력하십시오. 결과와 함께이 질문을 편집하십시오. 이것을 위해'ServerSocket'을 사용하십시오. Google은 ServerSocket 설명서를 제공합니다. 새로운 ServerSocket을 생성하고,'Socket client = server.accept();'와 연결을 수락 한 다음,'client'의 출력 스트림에서 데이터를 읽어서 그것을 출력하고 답장하십시오. – Aaron

+1

'ObjectOutputStream'과'ObjectInputStream'은이 상황에서 사용할 올바른 종류의 스트림이 아니며'writeObject()'와'readObject()'메소드가 아닙니다. 'OutputStreamWriter' (그 위에'BufferedWriter') 또는'DataOutputStream'과'InputStreamReader' (그 위에'BufferedReader'가있는)를 사용해야합니다. –

+1

또한 '0xF00041'은 무엇을 나타낼 것입니까? 당신은 당신이 그것을 3-4 바이트 정수가 아닌 8- 문자 스트링으로 보내고 있다는 것을 알고 있습니다. 그렇죠? 센서가 실제로 당신을 보낼 것으로 기대합니까? 프로토콜 문서를 제공 할 수 있습니까? –

답변

1

센서는 XML은 이진 5 바이트 헤더 선행되어야하지만 대신 8 자리 16 진수 문자열 인코딩 같이 헤더를 전송하는 기대한다.

또한 ObjectOutputStreamObjectInputStream을 사용하고 있습니다. 이는 Java 객체를 직렬화하기위한 것이지만 Java 객체를 보내거나 읽지는 않습니다. 그래서 이것들은 사용하기에 완전히 잘못된 스트림 클래스입니다.

코드에서 센서가 예상하는 내용을 전송하지 않으므로 수신 할 수있는 응답을 보내지 않고 코드가 올바르게 수신되지 않습니다.

(센서가 요청과 동일한 헤더 + XML 포맷으로 응답을 되돌려 보내고 가정) 대신이 같은 더 많은 것을 시도 :

import java.io.IOException; 
import java.io.DataOutputStream; 
import java.io.DataInputStream; 
import jva.io.BufferedInputStream; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import java.nio.charset.StandardCharsets; 
import java.nio.ByteBuffer; 

public class SocketClientExample { 
    public static void main(String[] args) throws UnknownHostException, IOException, ClassNotFoundException, InterruptedException { 
     System.out.println("Attempting connection to GE Reuter Stokes"); 

     // establish the socket connection to the server 
     // using the local IP address, if server is running on some other IP, use that 
     Socket socket = new Socket("10.212.160.4", 3010); 
     System.out.println("Socket Connected"); 

     // write to socket using OutputStream 
     DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); 

     // Initializing request content 
     byte[] request = "<Discovery><CommChannelName>Unknown</CommChannelName></Discovery>".getBytes(StandardCharsets.UTF_8); 

     // DataOutputStream.writeInt() writes in big endian and 
     // DataInputStream.readInt() reads in big endian. 
     // using a ByteBuffer to handle little endian instead. 

     byte[] header = new byte[5]; 
     ByteBuffer buf = ByteBuffer.wrap(header, 1, 4); 
     buf.order(ByteOrder.LITTLE_ENDIAN); 

     // Initializing request header 
     header[0] = (byte) 0xF0; 
     buf.putInt(request.length); 

     System.out.println("Sending request to Socket Server"); 

     // Sending request 
     dos.write(header); 
     dos.write(request); 
     dos.flush(); 

     System.out.println("Request was sent. Awaiting response."); 

     // read from socket using InputStream 
     DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 

     // Read response header 
     dis.readFully(header); 
     buf.flip(); 

     // Read response content 
     byte[] response = new byte[buf.getInt()]; 
     dis.readFully(response); 

     // convert the content into a string 
     String message = new String(response, StandardCharsets.UTF_8); 
     System.out.println("Message: " + message); 

     // close your resources 
     dis.close(); 
     dos.close(); 
     socket.close(); 

     Thread.sleep(100); 
    } 
} 
+0

당신은 생명의 은인입니다! 고맙습니다! –

관련 문제