我正在制作一个java telnet服务器。客户端是Windows telnet。我坚持发送数据,用其他键而不是" ENTER"键。 例如:您好,我是用户1。 在"用户1"之后当输入句号时,应该发送它 代码:
Player settings
答案 0 :(得分:0)
我认为问题在于你的代码。这段代码永远不会有效。
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命令提示符测试了这个,所以如果它不起作用,我就不知道你正在使用哪一个。