Java中的连接重置

时间:2012-04-24 04:21:20

标签: java java.util.scanner socketexception printwriter

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

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

    }

起初,客户和服务器都在等待对方说话,就像两个害羞的青少年一样。经过一些改变后,这种情况开始发生。我收到连接重置错误。请帮忙。期限!

2 个答案:

答案 0 :(得分:2)

在对等方关闭连接之前,

sc.hasNextByte()仍然有效。所以你永远不会离开这个循环。您需要在文件名之前发送文件名长度,以便知道有多少传入数据是文件名。然后读取文件名,打开文件,然后读取并复制流的其余部分,直到EOS。

答案 1 :(得分:0)

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

pw.write(fileName +“\ n”);

或者将某些编写者写入writeLine(fileName)。

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

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

....

}

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