给定这个python脚本:
import socket
import sys
import time
buf0 = "03".decode('hex')
buf1 = "0300".decode('hex')
buf2 = "8028".decode('hex')
package = buf0 + buf1 + buf2
HOST = "192.168.0.2"
PORT = 22
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(3)
s.connect((HOST,PORT))
s.send(package)
rec = s.recv(1024)
s.close()
我需要对Java执行完全相同的操作,现在我使用这个函数将hexstring转换为ascii字符串:
^{pr2}$我用Java套接字做了一些实验,但没有成功——本应接收数据包的应用程序接受连接,但在接收数据包时什么也不做,所以我想我做错了什么。在
使用python脚本一切正常。我可能在一些愚蠢的事情上失败了。有什么想法吗?在
以下是java代码:
String buff0 = "03";
String buff1 = "0300";
String buff2 = "8028";
String pack = convertHexToString(buff0) + convertHexToString(buff1) + convertHexToString(buff2);
Socket socket = null;
String host = "192.168.0.2";
try {
socket = new Socket(Inet4Address.getByName(host), 22);
System.out.println("connected");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader in = null;
PrintStream out = null;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintStream(socket.getOutputStream(), true);
out.print(pack);
System.out.println("sent");
in.read();
System.out.println("received");
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
我重写了很多次,结果总是不好。在
解决了发送字节数组的问题:
所以我基本上得到十六进制字符串,把它转换成字节数组,然后用OutputStream发送它。在
相关问题 更多 >
编程相关推荐