0

几天来,我一直在尝试修复此错误。真的。我只是不明白。代码很简单。为什么它不起作用?

    public class server
    {
public static void main(String[] args)
{
    String fileName = null;

    try
    {
        ServerSocket ss = new ServerSocket(9999, 3);

        Socket dataSocket = ss.accept();
        System.out.println("Server: Connection Established");

        InputStream is = dataSocket.getInputStream();
        //BufferedReader br = new BufferedReader(new InputStreamReader(is));
        Scanner sc = new Scanner(dataSocket.getInputStream());

        while(sc.hasNextByte())
        {
            System.out.println("True");
            fileName = fileName+sc.next();
        }

        FileWriter fw = new FileWriter("server"+fileName);
        while(dataSocket  != null)
        {
            fw.write(is.read());
        }

        fw.flush();
        dataSocket.close();
        ss.close();
            /*String[] nameParts;
            nameParts = fileName.split(".");
            File f = new File(nameParts[0]+"."+nameParts[1]);
            FileOutputStream fos = new FileOutputStream(f);
            System.out.println(nameParts[0]);*/
    }

    catch(Exception e)
    {
        e.printStackTrace();
    }
}

    }

以上是服务器代码。客户端代码如下:

    public class client 
    {
public static void main(String[] args) 
{
    // Read a file
    try 
    {
        Socket dataSocket = new Socket();

        dataSocket.connect(new InetSocketAddress(InetAddress.getLocalHost(), 9999));
        System.out.println("Client: Connection Established");

        OutputStream os = dataSocket.getOutputStream();
        PrintWriter pw = new PrintWriter(os);

        String fileName = "text.txt";

        pw.write(fileName);


        File f = new File(fileName);
        Scanner sc = new Scanner(f);

        /*while(sc.hasNextInt())
        {
            pw.write(sc.nextInt());
        }*/

        //pw.flush();
        //pw.close();

        //dataSocket.close();

        /*String[] nameParts = new String[2];
        nameParts = args[0].split(".");

        while(sc.hasNextByte())
        {
            os.write(sc.nextByte());5
        }*/
    }

    catch (Exception e) 
    {
        e.printStackTrace();
    }
}

    }

一开始,客户端和服务器都只是在等待对方说话,就像两个害羞的少年一样。经过一些更改,这开始发生。我收到连接重置错误。请帮忙。截止日期!

4

2 回答 2

2

sc.hasNextByte()在对等方关闭连接之前保持为真。所以你永远不会摆脱这个循环。您需要在文件名之前发送文件名长度,这样您就知道有多少传入数据是文件名。然后读取文件名,打开文件,读取并复制流的其余部分,直到 EOS。

于 2012-04-24T04:27:39.307 回答
0

或者,您可以使用留置权编写文件名,如下所示:

pw.write(fileName + "\n");

或者用户一些作家来 writeLine(fileName)。

在服务器端,使用 bufferedReader 逐行读取:

while ((line = br.readLine()) != null) {

....

}

如果客户端关闭,它可以完成循环。

于 2012-04-24T05:04:47.580 回答