在使用Socket来连接服务器时最简单的方式就是直接使用IP和端口,但Socket类中的connect方法并未提供这种方式,而是使用SocketAddress类来向connect方法传递服务器的IP和端口。虽然这种方式从表面上看要麻烦一些,但它会给我们带来另外一个好处,那就是网络地址的重用。
所谓网络地址的重用表现在两个方面:
1. 通过建立一个SocketAddress对象,可以在多次连接同一个服务器时使用这个SocketAddress对象。
2. 在Socket类中提供了两个方法:getRemoteSocketAddress和getLocalSocketAddress,通过这两个方法可以得到服务器和本机的网络地址。而且所得到的网络地址在相应的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;
- }
- }
- }
注:上面这段代码存在问题。在发生异常的情况下,会跳过计数,起不到该有的作用。这是个问题。欢迎各位留言,解决。谢谢。