关闭

JAVA TCP协议的发送接收

5221人阅读 评论(0) 收藏 举报

import java.net.*;
import java.io.*;
import java.util.*;

public class Tcp{

 public void receiver(int port)
    {
  ServerSocket serveSocket = null;
  Socket clientSocket = null;
  BufferedInputStream input = null;                                              
  byte[] buffer = new byte[1024];                                                    //平台生成的XML串
        ByteArrayOutputStream streamXML = new ByteArrayOutputStream();                    //请求数据存放对象

  try{
   serveSocket = new ServerSocket(port);                                           //在指定端口建立一个连接
   System.out.println("开始监听:");
   while (true){
    clientSocket = serveSocket.accept();                                         //收到一个信息,得到一个clientSocket
    InputStream inputStream = clientSocket.getInputStream();                     //数据缓冲区
             int count = 0;                                                            //每个缓冲区的实际数据长度
       try {
        input = new BufferedInputStream(inputStream);
        while ((count = input.read(buffer)) != -1){
         streamXML.write(buffer, 0, count);
        } 
       }catch (Exception e){
        e.printStackTrace();
       }finally{
        if (input != null){
         try {
          input.close();
         }catch (Exception f){
          f.printStackTrace();
         }
        }
       }

       System.out.println("收到如下信息:  " + streamXML.toString());
       streamXML.reset();
       inputStream.close();
    clientSocket.close();
   }
  }catch (Exception e){
   e.printStackTrace();
  }
    }
 
 public void send(String host,int port){
  
  byte[] buffer = new byte[1024];
  try{
  Socket socket = new Socket("192.168.61.146",20000);
  OutputStream outputStream = socket.getOutputStream();
  buffer = ("<package><head><requesttype>001</requesttype><user>PICC</user><code>12345678</code></head>"
      + "<body><policyno>00PICC1234567890</policyno><startdate>20070101</startdate><insured>zhangsan</insured></body>"
      + "<third><driverlist>"
      + "<driver><name>li1</name><age>20</age></driver>"
      + "</driverlist><date>19990909</date></third></package>").getBytes();
        outputStream.write(buffer);
        outputStream.flush();
        outputStream.close();
        socket.close();
  }catch (Exception e){
   e.printStackTrace();
  }
 }
 
 public static void main(String[] args) throws Exception {
  Tcp tcp = new Tcp();
  tcp.receiver(20000);
  //tcp.send("",20000);
 }
}
 

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:33488次
    • 积分:515
    • 等级:
    • 排名:千里之外
    • 原创:17篇
    • 转载:7篇
    • 译文:0篇
    • 评论:5条
    文章存档
    最新评论