Java远程登录服务器发送数据,字符串与其他键而不是"ENTER"



我正在制作一个java telnet服务器。客户端是windows telnet。我一直在发送数据,字符串用其他键而不是"回车"键。E.g:你好,我是用户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));

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

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命令提示符测试过了,所以如果它不起作用,我不知道你在用哪个。

相关内容

最新更新