OK, so far I made the basic system. On the server side, I have a classical server with a blocking ServerSocket. When a player connects, I create a new thread for him and communicate through InputStream and OutputStream. There’s no need for thread pooling, as I expect the number of players to be always less than 10.
On the client side I was using NIO and a non-blocking socket.
OK, so first of all, the client needs to log in by sending its user name and password. If this is ok, server personds with 0, otherwise 1.
I send the data like this:
public static boolean login(String userName, String password) throws IOException {
ByteBuffer buf = ByteBuffer.allocate(256);
buf.put(Command.LOGIN);
String str = "u="+userName+";p="+password;
buf.put(str.getBytes());
socket.write(buf);
buf.clear();
socket.read(buf);
if (buf.get(0) == Command.OK)
return true;
else
return false;
}
Command.LOGIN is a byte = 19
On the server side, I read the bytes into an array, then check the first byte for the command and proceed from there:
public void run() {
while (running) {
try {
byte[] bytes = new byte[300];
int i = 0;
int n = -1;
while (i < 256 && (n = input.read()) != -1) {
bytes[i] = (byte)n;
i++;
}
System.out.println("Received: " + bytes[0]);
// first byte contains the command
byte[] response = null;
switch (bytes[0]) {
case Command.LOGIN:
response = doLogin(bytes);
break;
.....
}
output.write(response);
output.flush();
As you can see, I always print out the command number I’m getting, so it should say that the command was 19. Instead, it always says:
Received: 0
Now, I checked it out, and if I connect to the server through telnet, and send 85 to it, then it will say that it has received 85, so obviously the problem is on the client’s side.
When I send a number from the server’s side (through OutputStream) the client will receive that number correctly.
Anyone can help me out what am I doing wrong?