i'm making a java telnet server. The client is the windows telnet. I'm stuck at the sending data,string with other key rather than "ENTER" key. E.g: Hello, i'm user 1. after "user 1" when the full stop is typed it should send that code:
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));
I believe the problem is your code here. This code would never work.
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
Try this and see if it works.
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");
}
when you run it do telnet localhost 5000
from the same computer. Windows telnet will send every time you press a key, so this will work with windows telnet not linux. You have to remember that TCP is stream based, unlike UDP which is packet based. I have tested this with Windows Command Prompt, so I don't know which one you are using if it doesn't work.