我应该将文件的数据包发送到服务器,然后将其打印出来。我遇到的问题是它只打印出每个奇数(0-nothing,1- text,2- nothing,4-text等)。这可以在服务器类中完成。谁能看出他的问题是什么?
客户端
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws Exception {
Client myCli = new Client();
myCli.run();
}
public void run() throws Exception {
Socket mySkt = new Socket("localhost", 9999);
PrintStream myPS = new PrintStream(mySkt.getOutputStream());
BufferedReader in = new BufferedReader(new FileReader("C:/Users/Thormode/Dropbox/Skole 2013-2014/java/da/src/da/tekst.txt"));
while (in.ready()) {
String s = in.readLine();
myPS.println(s);
}
in.close();
//BufferedReader myBR = new BufferedReader(new InputStreamReader(mySkt.getInputStream()));
//String temp = myBR.readLine();
//System.out.println(temp);
mySkt.close();
myPS.close();
}
}
服务器:
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args) throws Exception {
Server myServ = new Server();
myServ.run();
}
public void run() throws Exception {
ServerSocket mySS = new ServerSocket(9999);
Socket SS_accept = mySS.accept();
BufferedReader SS_BF = new BufferedReader(new InputStreamReader(
SS_accept.getInputStream()));
int i = 0;
String[] array = new String[10];
while (SS_BF.readLine() != null) {
array[i] = SS_BF.readLine();
i++;
}
for (int j = 0; j < i; j++) {
String temp = array[j];
System.out.println(temp);
}
SS_accept.close();
mySS.close();
}
}
答案 0 :(得分:0)
以下代码将循环读取两行:
String[] array = new String[10];
while (SS_BF.readLine() != null) { // reads a line and forgets it's value
array[i] = SS_BF.readLine(); // reads every second line and puts it into the array
i++;
}
所以你必须这样做:
String[] array = new String[10];
String line = SS_BF.readLine(); // read first line and store it to 'line'
while (line != null) {
array[i++] = line; // set 'line' to array
line = SS_BF.readLine(); // read next line
}
答案 1 :(得分:0)
while (SS_BF.readLine() != null) {
array[i] = SS_BF.readLine();
i++;
}
您正在呼叫SS_BF.readLine两次。由于这个原因,它丢弃了第一行。
while ((String line = SS_BF.readLine()) != null) {
array[i] = line;
i++;
}