简体   繁体   English

Java套接字连接

[英]Java socket connection

I've a target machine(*nix based) which is connected to my machine(local to my pc). 我有一台目标计算机(基于* nix)连接到我的计算机(本地到我的PC)。 I want to execute some commands on this target. 我想在此目标上执行一些命令。

So, I'm using Java socket to achieve the same. 因此,我正在使用Java套接字来实现相同的目的。

socket = new Socket("100.200.400.300", 23, null, 0 );
                         remote            local 

Here, after the above line - 在这里,在上述行之后-

socket.isConnected() returns true.

Now, I've I/O streams of this Socket object and I'm doing - 现在,我已经有了此Socket对象的I / O流,并且正在做-

while((string = bufferedReader.readLine()) != null) {
     outputStream.write(string .getBytes());
     outputStream.flush(); }

Buffered reader to read commands from a local file and write to the socket object for execution on the target machine. 缓冲读取器,用于从本地文件读取命令并写入套接字对象,以便在目标计算机上执行。 Below code to read from Socket - 下面的代码从套接字读取-

while((myIntVar = is.read()) != -1) {
//Below line prints some junk data ... hash, updaward arrow and spaces and then
// loop hangs to raise a Socket I/O exception.
System.out.println((char) i);
stringBuffer.append((char) i);}

Here, my understanding is that, as I already have the socket connection established, I can just pass my commands and those commands should get executed on the other side(correct me if am wrong). 在这里,我的理解是,由于已经建立了套接字连接,因此我可以传递命令,而这些命令应该在另一侧执行(如果错误,请更正)。

But this is not working. 但这是行不通的。 I'm getting junk characters as I've mentioned above and there is one more thing - I'm not passing username and password for establishing the socket connection - do I've to pass it as we do for telnet(how...? am lost here). 我已经收到上面提到的垃圾字符,还有另外一件事-我没有传递用于建立套接字连接的用户名和密码-我必须像为telnet一样传递它吗? ?在这里迷路了。

And, just for info - the above code is all that I've(no server or client code as mentioned in various other threads) . 而且,仅作为参考-上面的代码就是我所拥有的(没有其他线程中提到的服务器或客户端代码)。

Telnet does not quite use raw sockets as you have. Telnet并没有像您一样完全使用原始套接字。 Telnet has special ways of end lines and ending messages. Telnet具有特殊的端线和结束消息方式。 You will need to work out the correct protocol to use, there are actually several varying implementations of telnet. 您需要确定要使用的正确协议,实际上telnet有几种不同的实现。 It may be easier to use a library. 使用库可能会更容易。

An easy work around would be to filter any character that does not fall in the correct ascii range we want. 一个简单的解决方法是过滤不属于我们所需的正确ascii范围的任何字符。

private static String cleanMessage(String in) {
    StringBuilder sb = new StringBuilder();
    for (Character i : in.toCharArray()) {
        int charInt = i.hashCode();
        if (charInt >= 32 && charInt <= 126) {
            sb.append(i);
        }
    }
    return sb.toString();
}

The Apache Commons library has an implement of Telnet handling, with an example here Apache Commons库具有Telnet处理的实现, 此处有一个示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM