Search code examples
javatcpbytebuffersocketchannel

Cannot extract correct information from message received through SocketChannel


I am sending a string which has been converted into bytes using a DataOutput stream

// creates a client socket which connects to the first successor's server.
Socket clientSocket = new Socket(host, succ1_port);

// send the output_string to the first successor.
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
outToServer.writeBytes(output_string);

and then receiving them through a SocketChannel:

// accept connection
SocketChannel connectionSocket = tcpserver.accept(); // tcpserver is a ServerSocketChannel

ByteBuffer buf = ByteBuffer.allocate(48);

// store and print no. of bytes read
int bytes_read = connectionSocket.read(buf);
System.out.println("bytes read = " +bytes_read);
String from_client_string = new String(buf.array(), Charset.forName("UTF-8"));

The messages received are always of the format, "XXXX XXX" where X is any digit from 0-9.

I then try and separate these messages into two parts:

Pattern p = Pattern.compile("([0-9]{4}) ([0-9]{3})"); 
Matcher m = p.matcher(from_client_string);

if (m.matches()){   
  int filename = Integer.parseInt(m.group(1));
  int hash = Integer.parseInt(m.group(2));
  System.out.println("filename = " +filename);
  System.out.println("hash = " +hash);
else
  System.out.println("no match");   

The problem is, sometimes when I print out the string converted from the bytebuffer, its value changes... Usually it is correct like "1234 210" but on other occasions it may cut out a digit and display "1234 21". However even when it is correct, I don't get a match? I also found the number of bytes being read always changes...

Would anyone know what the problem here is?

Thanks for your help.


Solution

  • Thank you Peter! You're suggestion appears to be working :) I would vote you up but I don't have sufficient reputation.

    Sending the data:

    // creates a client socket which connects to the first successor's server.
    Socket clientSocket = new Socket(host, succ1_port);
    
    // send the output_string to the first successor.
    DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
    outToServer.writeUTF(output_string);
    
    outToServer.close();    
    clientSocket.close();
    

    Server Side (receiving the data)

    // accept connection
    SocketChannel connectionSocket = tcpserver.accept(); // tcpserver is a ServerSocketChannel
    
    DataInputStream inToServer = new DataInputStream(connectionSocket.socket().getInputStream());
    String from_client_string = inToServer.readUTF(); 
    

    The pattern matching stuff is the same as in the OP...except now it actually seems to work :)