一段Java socket代码

在使用Socket来连接服务器时最简单的方式就是直接使用IP和端口,但Socket类中的connect方法并未提供这种方式,而是使用SocketAddress类来向connect方法传递服务器的IP和端口。虽然这种方式从表面上看要麻烦一些,但它会给我们带来另外一个好处,那就是网络地址的重用。

    所谓网络地址的重用表现在两个方面:

    1. 通过建立一个SocketAddress对象,可以在多次连接同一个服务器时使用这个SocketAddress对象。

    2. 在Socket类中提供了两个方法:getRemoteSocketAddress和getLocalSocketAddress,通过这两个方法可以得到服务器和本机的网络地址。而且所得到的网络地址在相应的Socket对象关闭后任然可以使用。

DataInputStream   input = null;   

  1.   Socket socket = null;   
  2. //  InputStream input = null; // 输出流   
  3.   OutputStream output = null// 输入流   
  4.   InetSocketAddress inetSocketAddress = null;   
  5.   PrintWriter out = null;   
  6.   String text = null;   
  7.      
  8.   BufferedReader line = null;   
  9.   int communicateTime = 0// 当前已尝试连接的次数   
  10.   try {   
  11.    Properties props = BAConfiger.getProperties();//获取配置文件中的参数   
  12.    String socketIP = props.getProperty("socketIP");// IP   
  13.    int socketProt = Integer.parseInt(props.getProperty("socketProt"));// 端口   
  14.    int socketConnectionCount = Integer.parseInt(props.getProperty("socketConnectionCount"));// 最大连接次数   
  15.    int socketConnectionTime = Integer.parseInt(props.getProperty("socketConnectionTime"));// 超时时间   
  16.    int socketWateServerTime = Integer.parseInt(props.getProperty("socketWateServerTime"));// 超时时间   
  17.       
  18.    inetSocketAddress = new InetSocketAddress(socketIP, socketProt);   
  19.    // ------------创建连接------------   
  20.    socket = new Socket();   
  21.    while (communicateTime < socketConnectionCount) {   
  22.     socket.connect(inetSocketAddress, socketConnectionTime * 1000);   
  23.     if (socket.isConnected()) {   
  24.      System.out.println("连接服务器成功!");   
  25.      break;   
  26.     }   
  27.     communicateTime++;   
  28.    }   
  29.    if (socket.isConnected()) {   
  30.     output = socket.getOutputStream();   
  31.     input = new DataInputStream(socket.getInputStream());   
  32.     output.write(encryptText.getBytes());   
  33.     output.flush();// 发送信息至银联   
  34.     int avali = 0;   
  35.     for (int i = 0;i < socketWateServerTime; i++){   
  36.      avali = input.available();   
  37.      if (avali == 0){   
  38.       Thread.sleep(1000);   
  39.       System.out.println("银行没有返回信息,继续等待......");   
  40.      }else{   
  41.       System.out.println("返回的数据长度是: " + avali);   
  42.       byte aval[] = new byte[avali];   
  43.       int bytesRead = input.read(aval,0,avali);   
  44.       text = Pub.decodeStr(aval, "GB2312");   
  45.       System.out.println(">>>>>>>>>服务器返回的数据是: " + text);   
  46.       break;   
  47.      }   
  48.     }   
  49.    }

注:上面这段代码存在问题。在发生异常的情况下,会跳过计数,起不到该有的作用。这是个问题。欢迎各位留言,解决。谢谢。

猜你喜欢

转载自moor212.iteye.com/blog/1169189