【问题标题】:Program only printing out/receiving every other packet程序仅打印/接收每隔一个数据包
【发布时间】:2014-03-10 20:28:02
【问题描述】:

我应该将文件的数据包发送到服务器,然后将其打印出来。我遇到的问题是它只打印出每个奇数(0-无,1-文本,2-无,4-文本等)。这在服务器类中完成。谁能看出他的问题是什么?

客户

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


}

【问题讨论】:

    标签: java sockets udp packets


    【解决方案1】:

    以下代码将循环读取两行:

    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
    }
    

    【讨论】:

      【解决方案2】:
      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++;
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-03
        • 2014-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-04
        • 2016-01-08
        相关资源
        最近更新 更多