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
这里写图片描述
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是一个使用Java编写的TCP协议分析代码示例,仅供参考: ```java import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Socket; public class ProtocolAnalyzerClient { public static void main(String[] args) throws IOException { String hostName = "localhost"; int portNumber = 12345; try ( Socket socket = new Socket(hostName, portNumber); OutputStream out = socket.getOutputStream(); InputStream in = socket.getInputStream(); ) { // 发送数据包 String command = "GET"; String arg1 = "/index.html"; String arg2 = "HTTP/1.1"; String data = command + "," + arg1 + "," + arg2 + "\n"; out.write(data.getBytes()); // 接收响应数据包 byte[] buffer = new byte[1024]; int bytesRead = in.read(buffer); if (bytesRead > 0) { String response = new String(buffer, 0, bytesRead); // 解析响应数据包 System.out.println("Response: " + response); } } catch (IOException e) { System.out.println("Exception caught when trying to connect to server " + hostName + " on port " + portNumber); System.out.println(e.getMessage()); } } } ``` 此示例代码假设客户端将每个数据包作为以逗号分隔的字符串发送,并且每个数据包包含三个字段:命令、参数1和参数2。在主函数中,程序创建了一个Socket对象,并将其连接到指定的主机和端口号。然后,程序使用OutputStream来发送数据包,并使用InputStream来接收响应数据包。在发送数据包时,程序将数据包的三个字段作为字符串连接并写入OutputStream。在接收响应数据包时,程序读取InputStream中的字节,并将其转换为字符串。然后,程序解析响应数据包中的数据,并将其打印到控制台上。 当然,这只是一个简单的示例,实际的TCP协议分析器需要更多的代码来处理复杂的数据包、错误处理等问题。但是,这个示例可以帮助您了解如何使用Java编写TCP协议分析代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值