Skip to content
Advertisement

Send a 2D Matrix from Client to Server in Java using TCP connection (Socket Programming)

I need to send a 2D matrix from the client to the server-side using the following packages:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket; 

I have read a matrix from the user and I need to send to the server to perform certain operations on it. How do I send the complete matrix across? I am sending multiple variables and not just a matrix. I am sending integers and a matrix.

Advertisement

Answer

So after trying out something I thought could work, I found a simple solution to this problem.

Client-Side code

            // Make a new client side connection
            Socket clientSocket = new Socket("localhost", 9000);


            // Create an output stream
            DataOutputStream dataOutput = new DataOutputStream(clientSocket.getOutputStream());

            // Send data to the server

            // Send the number of nodes and the matrix
            dataOutput.writeInt(nodes);
            dataOutput.flush();
            for (int i = 0; i < nodes; i++)
                for (int j = 0; j < nodes; j++)
                    dataOutput.writeInt(adjMatrix[i][j]);
                    dataOutput.flush();

and the code on the server-side which would receive the matrix is as follows.

    // create a server socket and bind it to the port number 
    ServerSocket serverSocket = new ServerSocket(9000); 
    System.out.println("Server has been started");
    
    while(true){
        
        // Create a new socket to establish a virtual pipe 
        // with the client side (LISTEN)
        Socket socket = serverSocket.accept(); 
        
        // Create a datainput stream object to communicate with the client (Connect)
        DataInputStream input = new DataInputStream(socket.getInputStream()); 

     
        // Collect the nodes and the matrix through the data
        int nodes = input.readInt();
        int adjMatrix[][] = new int[nodes][nodes]; // Create the matrix
        for (int i = 0; i < nodes; i++)
            for (int j = 0; j < nodes; j++)
                adjMatrix[i][j] = input.readInt();
    }

This solution worked for me can be used to parse any type of data stream.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement