Socket with C # and java

2

Good morning, I'm writing an application where the socket server is in C # (because there are some drivers that have to be in C #) and the client in Java. I can make the communication perfectly between them, however when passing data, I have the following error:

  

System.ArgumentOutOfRangeException: Argument specified was outside the range of valid values.   Parameter Name: size      at System.Net.Sockets.NetworkStream.Read (Byte [] buffer, Int32 offset, Int32 size)      in tests.handleClinet.doChat () on d: \ c # \ socket \ tests \ handleClinet.cs: line 40

Server C # code:

//Class to handle each client request separatly
public class handleClinet
{
    TcpClient clientSocket;
    string clNo;
    public void startClient(TcpClient inClientSocket, string clineNo)
    {
        this.clientSocket = inClientSocket;
        this.clNo = clineNo;
        Thread ctThread = new Thread(doChat);
        ctThread.Start();
    }
    private void doChat()
    {
        int requestCount = 0;
        byte[] bytesFrom = new byte[10000];
        string dataFromClient = null;
        Byte[] sendBytes = null;
        string serverResponse = null;
        string rCount = null;
        requestCount = 0;
        while ((true))
    {
        try
        {
            requestCount = requestCount + 1;
            NetworkStream networkStream = clientSocket.GetStream();
            Console.WriteLine(" >> " + (int)clientSocket.ReceiveBufferSize);
            networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);
            dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);
            dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"));
            Console.WriteLine(" >> " + "From client-" + clNo + dataFromClient);

            rCount = Convert.ToString(requestCount);
            serverResponse = "Server to clinet(" + clNo + ") " + rCount;
            sendBytes = Encoding.ASCII.GetBytes(serverResponse);
            networkStream.Write(sendBytes, 0, sendBytes.Length);
            networkStream.Flush();
            Console.WriteLine(" >> " + serverResponse);
        }
        catch (Exception ex)
        {
            Console.WriteLine(" >> " + ex.ToString());
            return;
        }
    }
}

}

Client code: Java

public static void main(String[] args) throws IOException {

      String sentence;
      String modifiedSentence;
      BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
      Socket clientSocket = new Socket("localhost", 9999);
      DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
      sentence = inFromUser.readLine();
      outToServer.writeBytes(sentence + '\n');
      modifiedSentence = inFromServer.readLine();
      System.out.println("FROM SERVER: " + modifiedSentence);
      clientSocket.close();
}

New client in Java:

public class Cliente {

    public static void main(String[] args) {

        try {
            Socket s = new Socket("127.0.0.1", 9999);
            InputStream i = s.getInputStream();
            OutputStream o = s.getOutputStream();
            String str;
            while(true){
                byte[] line = new byte[100];
                System.in.read(line);
                o.write(line);
                i.read(line);
                str = new String(line);
                System.out.println(str.trim());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Thanks for the help.

    
asked by anonymous 05.04.2016 / 15:48

1 answer

2

Replace:

networkStream.Read(bytesFrom, 0, (int)clientSocket.ReceiveBufferSize);

By:

int read = networkStream.Read(bytesFrom, 0, bytesFrom.Length);

Replace:

dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom);

By:

dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom, 0 , read);

And still put all content after int read = into if , like this:

if ( read > 0 )
{
    ...
}

The explanation

.ReceiveBufferSize tells the size of the available buffer, not how much data it has in it. The method in this case is .Available . In fact, I suggest changing the first one for the other.

The problem with the first line that is replaced is that .ReceiveBufferSize can be much larger than bytesFrom.Length , which gives this error. .Read expects you to pass as much as you can read, and the maximum you can read is the size of bytesFrom , not the socket buffer size.

Well, this is important to see return of .Read because you do not know how many bytes were actually read. You can not trust .Available , you have to get the same return. This already follows the justification of the second substitution. As it was, you were always creating a string of 10,000 chars, even if you only received one byte.

The if is not important as long as it ensures that the socket is blocking. But if there is no guarantee, then if is required by a .Read can return after having read zero bytes, which gives error in several of the functions called subsequently.

    
06.04.2016 / 00:26