[英]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:我需要使用以下包将 2D 矩阵从客户端发送到服务器端:
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.
我正在发送整数和矩阵。
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.这个对我有用的解决方案可用于解析任何类型的数据流。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.