Java telnet 服务器发送数据,使用其他键而不是 "ENTER" 的字符串

Java telnet server send data,string with other key rather than "ENTER"

我正在制作一个 java 远程登录服务器。客户端是 windows telnet。我被困在发送数据,字符串与其他键而不是 "ENTER" 键。 例如:你好,我是用户 1。 在 "user 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));

我认为问题出在您的代码上。此代码永远不会工作。

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 命令提示符对此进行了测试,所以如果它不起作用,我不知道你使用的是哪个。