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;
}
}
}
java Socket 发送和接受信息
最新推荐文章于 2024-06-11 15:09:28 发布