将Python套接字代码转换为Java套接字代码

时间:2014-01-02 11:18:38

标签: java python sockets io

鉴于此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字符串:

public static String convertHexToString(String hex) {

StringBuilder sb = new StringBuilder();
StringBuilder temp = new StringBuilder();
for (int i = 0; i < hex.length() - 1; i += 2) {

    // grab the hex in pairs
    String output = hex.substring(i, (i + 2));
    // convert hex to decimal
    int decimal = Integer.parseInt(output, 16);
    // convert the decimal to character
    sb.append((char) decimal);

    temp.append(decimal);
}

return sb.toString();
}

我已经使用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();
}

我多次重写,但总是没有好结果。

1 个答案:

答案 0 :(得分:0)

解决了发送字节数组的问题:

    String buff0 = "03";
    String buff1 = "0300";
    String buff2 = "8028";

    String packet = buff0 + buff1 + buff2;

    byte[] b = new BigInteger(packet,16).toByteArray();



    try {
        Socket socket = new Socket("192.168.0.2", 22);
        OutputStream socketOutputStream = socket.getOutputStream();
        socketOutputStream.write(b);
        InputStream socketInput = socket.getInputStream();
        System.out.println(socketInput.read());
        socket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

所以我基本上得到十六进制字符串,将其转换为字节数组并使用OutputStream发送它。