使用tcp连接(套接字编程)在java中将2d矩阵从客户端发送到服务器

6qqygrtg  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(353)

我需要使用以下软件包将2d矩阵从客户端发送到服务器端:

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

我已经从用户那里读取了一个矩阵,我需要发送到服务器来对它执行某些操作。我如何发送完整的矩阵?我正在发送多个变量,而不仅仅是一个矩阵。我正在发送整数和矩阵。

nnt7mjpx

nnt7mjpx1#

所以在尝试了一些我认为可行的方法之后,我找到了一个解决这个问题的简单方法。
客户端代码

// 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();

服务器端接收矩阵的代码如下。

// 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();
    }

这个为我工作的解决方案可以用来解析任何类型的数据流。

相关问题