简体   繁体   中英

Java TCP socket program to send and read [x] bytes array. How to loop, sout and sent correctly

I'm new with sockets and writing basic Java Client-to-Server-to-Client program that sends in this case length of the message outToServer.writeInt(message.length); and byte[] message = new byte[10]; array to Server that reads and prints it to console and then modifies few bytes in the array and then sends it back to the Client. Client receives the array, reads it and and prints it to console.

My problem is that it prints only:

byte array received from server class: 

0
0
0
0
0
0
0
0
0
0
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

when it should print some modified bytes with different numbers.

I assume there's some problem with for loop or in the reading part of the received bytes. Should i use readFully or something similar and how to do it correctly to loop the values i want?

Many thanks.

Client:

class TCPClient2 {

    public static void main(String argv[])
    {


        try {
            System.out.println("Client started");
            Socket clientSocket = new Socket("localhost", 8080);
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            System.out.println("\nByte array printed before sending to server:\n");

            byte[] message = new byte[10];
            //byte[] message = new byte[] { -1, -128, 1, 127, 23, 23, 23, 23, 23, 10 }; // you can try these too
            message[0] = 1; // changes the first byte of the array


            for(int i = 0; i < message.length; i++) {
                System.out.println(message[i]);     //prints byte array BEFORE being sent to server
            }
            System.out.println(Arrays.toString(message)); //prints byte array BEFORE being sent to server as String
            System.out.println("\n");


            outToServer.writeInt(message.length); // write length of the message
            outToServer.write(message);           // write the message
            //
            //
            // Message -array is now sent to Server
            //
            // Waiting for answer
            //


            // Answer is now received from Server
            System.out.println("byte array received from server class: \n");
            DataInputStream inFromClient = new DataInputStream(clientSocket.getInputStream());


            int length = inFromClient.readInt(); // read length of incoming message
                    /*
                    if(length>0) {
                        byte[] message = new byte[length];
                        dIn.readFully(message, 0, message.length); // read the message
                    }
                        */

            byte[] messageFromServer = new byte[length];
            for(int i = 0; i < messageFromServer.length; i++) {
                System.out.println(messageFromServer[i]);//prints received byte array
            }
            System.out.println(Arrays.toString(messageFromServer));//prints received byte array as a string

        }catch (Exception e) {
            e.printStackTrace();
        }


        }

    }

Server:

class TCPServer2 {

    public static void main(String argv[])
    {

                try
                {
                    System.out.println("waiting for connections");
                    ServerSocket welcomeSocket = new ServerSocket(8080);
                    Socket connectionSocket = welcomeSocket.accept();
                    System.out.println("connection established");

                    DataInputStream inFromClient =
                            new DataInputStream(connectionSocket.getInputStream());         //receive byte array from client

                    int length = inFromClient.readInt(); // read length of incoming message
                    /*
                    if(length>0) {
                      byte[] message = new byte[length];
                        inFromClient.readFully(message, 0, message.length); // readFully the message, but how?
                    }
                    */

                    byte[]message = new byte[length];
                    for(int i = 0; i < message.length; i++) {
                        System.out.println(message[i]); // print array
                    }

                    System.out.println(Arrays.toString(message)); // print array as string
                    System.out.println("message from client printed");

                    message[0]= 1;      //change bytes of the received array
                    message[9]=1;       //change bytes of the received array

                    DataOutputStream outToClient =
                            new DataOutputStream(connectionSocket.getOutputStream()); //send byte array with changes back to the client

                    outToClient.writeInt(message.length); // write length of the message
                    outToClient.write(message);           // write the message

                    System.out.println("message to client sent");



                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

    }
     

         

The problem is that you did not read the data from the socket, but only cycled through the local array.

You need to change these pieces of code:

1) Server

from:

            byte[]message = new byte[length];
            for(int i = 0; i < message.length; i++) {
                System.out.println(message[i]); // print array
            }

to:

            byte[]message = new byte[length];
            for(int i = 0; i < message.length; i++) {
                message[i] = inFromClient.readByte();
                System.out.println(message[i]); // print array
            }

2) client

from:

    byte[] messageFromServer = new byte[length];
    for(int i = 0; i < messageFromServer.length; i++) {
        System.out.println(messageFromServer[i]);//prints received byte array
    }

to:

    byte[] messageFromServer = new byte[length];
    for(int i = 0; i < messageFromServer.length; i++) {
          messageFromServer[i] = inFromClient.readByte();
        System.out.println(messageFromServer[i]);//prints received byte array
    }

An example is without specifying controls, the length of the array, ...

Or with your function readFully

1) Server

    int length = inFromClient.readInt(); // read length of incoming message
    byte[] message = new byte[length];
    if (length > 0) {
        inFromClient.readFully(message, 0, message.length); // readFully the message, but how?
    }

    for (int i = 0; i < message.length; i++) {
        System.out.println(message[i]); // print array
    }

2) Client

    int length = inFromClient.readInt(); // read length of incoming message
    byte[] messageFromServer = new byte[length];
    if (length > 0) {
        inFromClient.readFully(messageFromServer, 0, messageFromServer.length); // read the message
    }

    for (int i = 0; i < messageFromServer.length; i++) {
        System.out.println(messageFromServer[i]);//prints received byte array
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM