【问题标题】:Java telnet server send data,string with other key rather than "ENTER"Java telnet 服务器发送数据,字符串与其他键而不是“ENTER”
【发布时间】:2016-04-12 23:25:27
【问题描述】:

我正在制作一个 java telnet 服务器。客户端是windows telnet。我被困在发送数据,字符串与其他键而不是“ENTER”键。 例如:您好,我是用户 1。 在“用户 1”之后,当输入句号时,它应该发送 代码:

byte[] buff = new byte[4096];
String str = new String(buff, "UTF-8");
do {
    if ( buff[0] == 46 ) {  //46-[.]
        System.out.println("46-[.]  " + buff[0]);
        //incoming.getInputStream().read(buff);
    }
    incoming.getInputStream().read(buff);
} while ((buff[0] != 27) && (!done));

【问题讨论】:

  • 你是问如何让windows telnet客户端在按下return之前发送数据?
  • 它与你的服务器如何无关,这取决于你的客户端使用什么来触发发送数据
  • 那个windows客户端写的东西。之后,而不是 ENTER 发送它以使用其他键。
  • 不清楚你在问什么。在您的问题中发布代码,并且可以使用sen 命令使用telnet 发送字符串。
  • 字节[] buff = 新字节[4096]; String str = new String(buff, "UTF-8"); do { if ( buff[0] == 46 )// 46-[.] { System.out.println("46-[.] " + buff[0]); //incoming.getInputStream().read(buff); } 传入.getInputStream().read(buff); } while ( (buff[0] != 27) && (!done) ); ---这里我用ESC键停止连接---

标签: telnet


【解决方案1】:

我认为问题在于您的代码。这段代码永远不会工作。

byte[] buff = new byte[4096];
String str = new String(buff, "UTF-8"); //the buffer is initialized to 0 so we get no String
do {
    if ( buff[0] == 46 ) {  //46-[.]
        System.out.println("46-[.]  " + buff[0]);
        //incoming.getInputStream().read(buff);
    }
    incoming.getInputStream().read(buff);   //reading into an array
} while ((buff[0] != 27) && (!done));       //and only checking first index

试试这个,看看它是否有效。

public static void main(String[] args) throws IOException {
    //listen on tcp port 5000
    ServerSocket ss = new ServerSocket(5000);
    Socket s = ss.accept();

    //create an input/output stream
    InputStream in = new BufferedInputStream(s.getInputStream());
    PrintWriter out = new PrintWriter(s.getOutputStream(), true);

    byte[] buffer = new byte[0x2000];
    for (int bufferlen = 0, val; (val = in.read()) != -1;) {
        if (val == '.') { //if token is a '.' no magic numbers such as 46
            String recv = new String(buffer, 0, bufferlen);
            System.out.printf("Received: \"%s\"%n", recv);
            bufferlen = 0; //reset this to 0
        } else if (val == 27) {
            s.close();
            break;
        } else { //character is not a . so add it to our buffer
            buffer[bufferlen++] = (byte)val;
        }
    }
    System.out.println("Finished");
}

当您在同一台计算机上运行它时,请执行telnet localhost 5000。 Windows telnet 将在您每次按键时发送,因此这将适用于 windows telnet 而不是 linux。你必须记住 TCP 是基于流的,不像 UDP 是基于数据包的。我已经用 Windows 命令提示符对此进行了测试,所以如果它不起作用,我不知道您使用的是哪一个。

【讨论】:

    猜你喜欢
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    • 2014-07-14
    • 2011-05-30
    • 2014-04-05
    • 1970-01-01
    • 2017-11-30
    • 2016-02-10
    相关资源
    最近更新 更多