Java使用TCP协议获取XML及其处理

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

本示例使用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

           

给我老师的人工智能教程打call!http://blog.csdn.net/jiangjunshow
这里写图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值