package com.test;
import java.io.DataInputStream;
public class socketDemo {
public static void main(String[] args) {
send();
}
public static String send() {
Socket socket = null;
String info = "";
OutputStream out=null;
InputStream in=null;
try {
// socket用于连接某个服务器
socket = new Socket("localhost", 12351);
out = socket.getOutputStream();
in = socket.getInputStream();
String reqbody = "390000000046464646";//发送内容
byte[] msgByteArray = hexString2bytes(reqbody);
out.write(msgByteArray);
out.flush();
//获取返回
byte[] datalength = new byte[2];
in.read(datalength, 0, datalength.length);
String datLen = bytesToHexString(datalength);
int headLen = Integer.valueOf(headLen, 16).intValue();
byte[] message = new byte[headLen];
DataInputStream dis = new DataInputStream(in);
dis.readFully(message);
info = bytesToHexString(message);
System.out.println("收到返回:" + info);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // 这时候可以关闭socket连接
}
}
return info;
}
public static String bytesToHexString(byte[] bytes) {
StringBuilder stringBuilder = new StringBuilder();
if ((bytes == null) || (bytes.length <= 0)) {
return "";
}
for (byte b : bytes) {
int v = b & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
public static byte[] hexString2bytes(String asciiStr) {
String hexStr;
int len = asciiStr.length();
if (len % 2 != 0) {
hexStr = "0" + asciiStr;
} else {
hexStr = asciiStr;
}
byte[] bytes = new byte[hexStr.length() / 2];
for (int i = 0; i < bytes.length; i++) {
try {
bytes[i] = (byte) (0xff & Integer.parseInt(
hexStr.substring(i * 2, i * 2 + 2), 16));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
return bytes;
}
}