Java使用TCP協議擷取XML及其處理

來源:互聯網
上載者:User

本樣本使用Java類比Socket伺服器端,由用戶端向伺服器發送請求資訊後,擷取伺服器XML資訊,然後解析處理。

1、Socket伺服器端

import java.net.*;import java.io.*;public class TCPServer {public static void main(String args[]){try{int serverPort=7896;ServerSocket listenSocket=new ServerSocket(serverPort);while(true){Socket clientSocket=listenSocket.accept();Connection c=new Connection(clientSocket);}}catch(IOException e){System.out.println("Listen:"+e.getMessage());}}}class Connection extends Thread{DataInputStream in;DataOutputStream out;Socket clientSocket;public Connection(Socket aClientSocket){try{clientSocket=aClientSocket;in=new DataInputStream(clientSocket.getInputStream());out=new DataOutputStream(clientSocket.getOutputStream());this.start();}catch(IOException e){System.out.println("Connection:"+e.getMessage());}}public void run(){try{ String data=in.readUTF();//out.writeUTF(data);if(data.equals("ABC")){out.writeUTF("<result><!-- code: 0 - error, 1 - success --><code>0</code><weight>111.33</weight><unit>kg</unit><errmsg></errmsg></result>");}}catch(EOFException e){System.out.println("EOF:"+e.getMessage());}catch(IOException e){System.out.println("IO:"+e.getMessage());}finally {try{clientSocket.close();} catch(IOException e){/*關閉失敗*/}}}}

2、用戶端向伺服器發送請求,然後擷取XML串。

//測試TCP通訊protected void onBoReadNoTest() throws Exception {Socket soc = null;InputStreamReader isr = null;// 定義一個可讀輸入資料流String data = "";BufferedReader bf = null;// 定義一個BufferedReader類型的讀內容的引用InetAddress addr = InetAddress.getByName("127.0.0.1");int serverPort = 7896;if (addr.isReachable(5000)) {System.out.println("SUCCESS - ping " + addr+ " with no interface specified");try {soc = new Socket(addr, serverPort);System.out.println("Socket Success!");DataInputStream in = new DataInputStream(soc.getInputStream());DataOutputStream out=new DataOutputStream(soc.getOutputStream());out.writeUTF("ABC");//BufferedReader brin  = new BufferedReader(new InputStreamReader(soc.getInputStream()));System.out.println("DataInputStream Success!");data = in.readUTF();//System.out.println("接收到的資料:" + brin.readLine());//isr = new InputStreamReader(soc.getInputStream());// 建立一個來自通訊端soc的可讀輸入資料流//bf = new BufferedReader(isr);// 把soc的可讀輸入資料流作為參數建立一個BufferedReader//data = bf.readLine();// 以每行為單位讀取從用戶端發來的資料System.out.println("接收到的資料:" + data);this.DOM(data);//in.close();} catch (UnknownHostException e) {System.out.println("Socket Error:" + e.getMessage());} catch (EOFException e) {System.out.println("EOF:" + e.getMessage());} catch (IOException e) {System.out.println("IO:" + e.getMessage());} finally {if (soc != null)try {soc.close();} catch (IOException e) {/* close failed */}}} else {System.out.println("FAILURE - ping " + addr+ " with no interface specified");}}

3、XML解析處理

//DOM解析方法public void DOM(String data) {          long lasting = System.currentTimeMillis();            try {              //File f = new File("F:/xmltest.xml");  //        FileInputStream fis=new FileInputStream("data.xml");//        BufferedInputStream bis=new BufferedInputStream(fis);//        DataInputStream dis=new DataInputStream(bis);        byte[] b = data.getBytes();        InputStream inp = new ByteArrayInputStream(b);                    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();              DocumentBuilder builder = factory.newDocumentBuilder();              Document doc = builder.parse(inp);              NodeList nl = doc.getElementsByTagName("result");              for (int i = 0; i < nl.getLength(); i++) {                  System.out.println("||code:  |"+ doc.getElementsByTagName("code").item(i).getFirstChild().getNodeValue());                   System.out.println("||weight:  |"+ doc.getElementsByTagName("weight").item(i).getFirstChild().getNodeValue());                  System.out.println("||unit:  |"+ doc.getElementsByTagName("unit").item(i).getFirstChild().getNodeValue());                  System.out.println("||errmsg:  |"+ doc.getElementsByTagName("errmsg").item(i).getFirstChild().getNodeValue());                 }          } catch (Exception e) {              e.printStackTrace();          }          System.out.println("DOM RUNTIME:"                  + (System.currentTimeMillis() - lasting) + " MS");      }  

本文由小李專欄原創,轉載請註明【轉自:http://blog.csdn.net/softwave/article/details/8947771】

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.