我目前正在开发一个Java项目,我在服务器上有一个20个整数的大数组,我必须以5个块的形式将它发送到客户端。我只能发送第一个块。
如何一个接一个地发送块?
服务器代码:
public class SocketServer {
private ServerSocket serverSocket;
private int port;
String in;
public SocketServer(int port) {
this.port = port;
}
public Socket start() throws IOException {
System.out.println("Starting the server at port:" + port);
serverSocket = new ServerSocket(port);
//Listen for clients. Block till one connects
System.out.println("Waiting...");
Socket client = serverSocket.accept();
//A client has connected to this server. Send welcome message
//sendWelcomeMessage(client /*y*/);
return client;
}
public void sendWelcomeMessage(Socket client,int[]z) throws IOException {
ObjectInputStream sI = new ObjectInputStream(client.getInputStream());
ObjectOutputStream sO = new ObjectOutputStream(client.getOutputStream());
sO.writeObject(z);
sI.close();
sO.flush();
sO.close();
}
}
客户代码:
public class SocketClient {
Scanner c = new Scanner(System.in);
private String hostname;
private int port;
Socket socketClient;
public SocketClient(String hostname, int port){
this.hostname = hostname;
this.port = port;
}
public void connect() throws UnknownHostException, IOException{
System.out.println("Attempting to connect to "+hostname+":"+port);
socketClient = new Socket(hostname,port);
System.out.println("Connection Established");
}
public int[] readResponse() throws IOException, ClassNotFoundException{
int[] x = new int[5];
ObjectOutputStream cO = new ObjectOutputStream(socketClient.getOutputStream());
ObjectInputStream cI = new ObjectInputStream(socketClient.getInputStream());
cO.writeObject(x);
while(socketClient.isConnected()){
x = (int[]) cI.readObject();
for (int i = 0; i < 5; i++){
System.out.println(x[i]);
}
}
/*for (int i = 0; i < 5; i++){
System.out.println(x[i]);
}*/
cO.close();
cI.close();
return x;
}
}