java Socket 发送和接受信息

DataInputStream   input = null;
  Socket socket = null;
//  InputStream input = null; // 输出流
  OutputStream output = null; // 输入流
  InetSocketAddress inetSocketAddress = null;
  PrintWriter out = null;
  String text = null;
  
  BufferedReader line = null;
  int communicateTime = 0; // 当前已尝试连接的次数
  try {
   Properties props = BAConfiger.getProperties();//获取配置文件中的参数
   String socketIP = props.getProperty("socketIP");// IP
   int socketProt = Integer.parseInt(props.getProperty("socketProt"));// 端口
   int socketConnectionCount = Integer.parseInt(props.getProperty("socketConnectionCount"));// 最大连接次数
   int socketConnectionTime = Integer.parseInt(props.getProperty("socketConnectionTime"));// 超时时间
   int socketWateServerTime = Integer.parseInt(props.getProperty("socketWateServerTime"));// 超时时间
   
   inetSocketAddress = new InetSocketAddress(socketIP, socketProt);
   // ------------创建连接------------
   socket = new Socket();
   while (communicateTime < socketConnectionCount) {
    socket.connect(inetSocketAddress, socketConnectionTime * 1000);
    if (socket.isConnected()) {
     System.out.println("连接服务器成功!");
     break;
    }
    communicateTime++;
   }
   if (socket.isConnected()) {
    output = socket.getOutputStream();
    input = new DataInputStream(socket.getInputStream());
    output.write(encryptText.getBytes());
    output.flush();// 发送信息至银联
    int avali = 0;
    for (int i = 0;i < socketWateServerTime; i++){
     avali = input.available();
     if (avali == 0){
      Thread.sleep(1000);
      System.out.println("银行没有返回信息,继续等待......");
     }else{
      System.out.println("返回的数据长度是: " + avali);
      byte aval[] = new byte[avali];
      int bytesRead = input.read(aval,0,avali);
      text = Pub.decodeStr(aval, "GB2312");
      System.out.println(">>>>>>>>>服务器返回的数据是: " + text);
      break;
     }
    }
   }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值