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

2024-10-01 11:33:16 发布

您现在位置:Python中文网/ 问答频道 /正文

给定这个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();
}

我重写了很多次,结果总是不好。在


Tags: inimportnewclosestringsocketoutsystem
1条回答
网友
1楼 · 发布于 2024-10-01 11:33:16

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

    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发送它。在

相关问题 更多 >