【发布时间】:2018-05-03 08:39:27
【问题描述】:
有人可以演示如何通过 TCP 连接将字节数组从发送方程序发送到 Java 中的接收方程序。 这是一个来源
public class TCPClient
{
public static final String SERVER_IP ="********";
public static final int SERVER_PORT = 8022;
public static void main(String[] args) throws Exception
{
System.out.println("Client Started..." +hostAvailabilityCheck());
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
socket .setSoTimeout(10000);
DataInputStream is = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
DataOutputStream os = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
String sendapduString2 = "someapducommand";//get info
byte[] sendapdu2 = hexStringToByteArray(sendapduString2);
send(os, sendapdu2);
System.out.println("Data sent to Server ; Message = " );
try
{
while (true)
{
// Receive Server Response
byte[] byteData = receive(is);
String responseData = new String(byteData);
System.out.println("Server Response = " + responseData.trim());
}
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+ Character.digit(s.charAt(i + 1), 16));
}
return data;
}
public static boolean hostAvailabilityCheck() {
try (Socket s = new Socket(SERVER_IP, SERVER_PORT)) {
return true;
} catch (IOException ex) {
/* ignore */
}
return false;
}
/**
* Method receives the Server Response
*/
public static byte[] receive(DataInputStream is) throws Exception
{
try
{
byte[] inputData = new byte[1024];
is.read(inputData);
return inputData;
}
catch (Exception exception)
{
throw exception;
}
}
/**
* Method used to Send Request to Server
*/
public static void send(DataOutputStream os, byte[] byteData) throws Exception
{
try
{
os.write(byteData);
os.flush();
}
catch (Exception exception)
{
throw exception;
}
}
} 如您所见,我编写了将字符串转换为十六进制字节数组的函数。 我想将我的字节数组发送到服务器,响应应该是十六进制字节数组。 这是我的结果
Exception: Read timed out
谁能告诉我,我的来源有什么问题?
【问题讨论】: