客户端/服务器应用

时间:2010-06-09 07:39:23

标签: java

伙计们谁能告诉我,我在这里做错了什么?以下是Client,main,Server,main四个文件。尝试从Server.readLine()后,我在客户端出现错误。
错误:客户端软件错误导致连接中止:recv失败

            package client;
            import java.io.*;
            import java.net.*;
            import java.util.Scanner;

            public class Client
            {
            private PrintWriter toServer;
            private BufferedReader fromServer;
            private Socket socket;
            public Client( )throws IOException
                {
                socket = new Socket("127.0.0.1",3000);
            }
            public void openStreams() throws IOException
                {

            //
            //        InputStream is = socket.getInputStream();
            //        OutputStream os = socket.getOutputStream();
            //        fromServer = new BufferedReader(new InputStreamReader(is));
            //        toServer = new PrintWriter(os, true);

                toServer = new PrintWriter(socket.getOutputStream(),true);
                fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            }
            public void closeStreams() throws IOException
                {
                fromServer.close();
                toServer.close();
                socket.close();
            }
            public void run()throws IOException
                {
                openStreams();
                String msg = "";
                Scanner scanner = new Scanner(System.in);
                toServer.println("Hello from Client.");
            //    msg = scanner.nextLine();
                while (msg != "exit")
                {
                    System.out.println(">");
            //        msg = scanner.nextLine();
                    toServer.println("msg");
                    String tmp = fromServer.readLine();
                    System.out.println("Server said: " + tmp);
                }
                closeStreams();
            }
            }



        package server;
        import java.net.*;
        import java.io.*;

        public class Server
        {
        private ServerSocket serverSocket;
        private Socket socket;
        private PrintWriter toClient;
        private BufferedReader fromClient;
        public void run() throws IOException
            {
            System.out.println("Server is waiting for connections...");
            while (true)
            {
                openStreams();
                processClient();
                closeStreams();
            }

        }
        public void openStreams() throws IOException
            {
            serverSocket = new ServerSocket(3000);
            socket = serverSocket.accept();
            toClient = new PrintWriter(socket.getOutputStream(),true);
            fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        }
        public void closeStreams() throws IOException
            {
            fromClient.close();
            toClient.close();
            socket.close();
            serverSocket.close();
        }
        public void processClient()throws IOException
            {
            System.out.println("Connection established.");
            String msg = fromClient.readLine();
            toClient.println("Client said " + msg);
        }
        }


    package client;

    import java.io.IOException;


    public class Main {

        /**
         * @param args the command line arguments
         */
        public static void main(String[] args) {
            // TODO code application logic here

            try
            {
                 Client client = new Client();
                 client.run();
            }
            catch(IOException e)
            {
                 System.err.println("Error in Client " + e.getMessage());
            }
        }

    }



package server;

import java.io.IOException;


public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        Server server = new Server();
        try
        {
        server.run();
        }
        catch(IOException e)
        {
            System.err.println("Error in Server " + e.getMessage());
        }
    }

}

2 个答案:

答案 0 :(得分:2)

您的服务器端已全部混乱。你需要另一个类,称之为Connection,或者实现Runnable的ConnectedClient;将Socket作为构造函数参数;并为特定客户端执行所有服务器端I / O.目前,您将这一切与您的Server类混合在一起。您的Server类应该做的就是创建一个ServerSocket,并进入一个接受套接字并创建Connection对象并为它们启动线程的循环。 Server的run()方法中的Socket对象只是一个本地对象,关联的输入/输出流或读取器/写入器属于Connection类,而不属于Server类。

这样你就可以同时处理多个客户,而不会让他们彼此踩踏。

您的下一个问题是readLine()在另一端关闭连接时返回null。每次调用readLine()时,必须先测试 first ,然后再进行任何其他处理。

接下来,每次在使用Socket时得到SocketException或者除了SocketTimeoutException以外的IOException都会死掉 - 关闭它,忘记该客户端并在服务器中发生线程时退出该线程。

答案 1 :(得分:2)

发布的代码在客户端的无限循环中运行。 猜测哪一行取消注释(Client.java中的最后scanner.nextLine())后,我注意到以下问题:

  1. 客户端保持连接打开,但服务器在收到第一条消息后关闭。
  2. 谓词msg != "exit"在Java中始终为true - 使用String.equals()
  3. 正在运行的Server.processClient是:

    public void processClient()throws IOException
    {
        String msg = null;
        do {
            msg = fromClient.readLine();
            toClient.println("Client said " + msg);
        } while (!"exit".equals(msg));
    }
    

    正在运行的Client.run是:

    public void run()throws IOException
    {
        openStreams();
        String msg = "";
        Scanner scanner = new Scanner(System.in);
        while (!"exit".equals(msg))
        {
            System.out.print(">");
            msg = scanner.nextLine();
            toServer.println(msg);
            String tmp = fromServer.readLine();
            System.out.println("Server said: " + tmp);
        }
        closeStreams();
    }
    

    +评论:我专注于纠正明显的错误。 EJP的答案为您提供了如何使代码更好的良好指导,包括处理同时连接,正确使用线程等。