服务器 - 客户端通信问题

时间:2011-04-26 15:26:13

标签: java sockets tcp

我正在使用Java上的客户端 - 服务器程序示例。我遇到了这样一个问题: 我使用8080端口和本地主机启动服务器,而不是启动客户端并发出请求。一旦请求完成两个程序关闭theri套接字,所以我不能重复我的行为。如何使用同一客户端和同一服务器发出多个请求?

    public class Network extends Thread
{
    MasterEdit ME = new MasterEdit();
        private Socket _socket;
        InputStream is; //Data streams
        OutputStream os;
        /**
         * Network class constructor
         */
        public Network(int port, int backlog, InetAddress address)
        {
                //We create an object of SocketFactory
                SocketFactory sf = new SocketFactory();
                //Save server socket
                ServerSocket ss = null;

                try
                {
                        if(address == null) //If there is no host
                        {
                                if(backlog <= 0) //If backlog is not given we create it with port
                                {  ss = sf.createServerSocket(port);
                                    System.out.println("Success");
                                }
                                else
                                        ss = sf.createServerSocket(port, backlog); //If backlog is given we just create it
                        }
                        else
                                ss = sf.createServerSocket(port, backlog, address); //If everything is given we create it using data
                }
                catch(Exception e)
                {
                        //Exception with creation of socket
                        System.err.println("Failed open server socket");
                        System.exit(1); //Stop program and send 1 as a exception-code
                }

                while(true) //Listening to the socket
                {
                        try 
                        {
                                StartThread(ss.accept()); //If client has connected we send him to the daemon
                        } 
                        catch (IOException e) 
                        {
                                e.printStackTrace();
                        }
                }

        }

        /**
         * Start daemon-tool when client has connected
         */
        private void StartThread(Socket ss)
        {
                _socket = ss; //initializing of global variable

                setDaemon(true); //anounce that new potok is daemon
                setPriority(NORM_PRIORITY); //set the priority
                start(); //Start it
        }

        @Override
        public void run()
        {   
                byte buffer[] = new byte[64*1024]; //buffer in 64 kb
                try
                {
                        is = _socket.getInputStream();
                        os = _socket.getOutputStream(); //Initializing the output stream to a client
                        String toClient = SearchRequest(new String(buffer, 0, is.read(buffer)));
                        os.write(toClient.getBytes()); //Sending an answer
                }
                catch(Exception e)
                {
                        e.printStackTrace();
                }

        }

        private String SearchRequest(String request)
        {
                String info = ""; //Initializing of a variable

                if(request.equalsIgnoreCase("info")) //Check the request
                {
                        //Adding data
                        info += "Virtual Machine Information (JVM)n";
                        info += "JVM Name: " + System.getProperty("java.vm.name")+"n";
                        info += "JVM installation directory: " + System.getProperty("java.home")+"n";
                        info += "JVM version: " + System.getProperty("java.vm.version")+"n";
                        info += "JVM Vendor: " + System.getProperty("java.vm.vendor")+"n";
                        info += "JVM Info: " + System.getProperty("java.vm.info")+"n";
                        return info; //Give the answer
                }
                if(request.charAt(0)=='0') {
                    StringTokenizer rm = new StringTokenizer(request, " \t\n\r,:");
                    rm.nextToken();
                    ME.MasterDell(Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()), Double.parseDouble(rm.nextToken()));
                    return "Successfully deleted";
                }
                if(request.charAt(0)=='1'){
                    StringTokenizer temp = new StringTokenizer(request, " \t\n\r,:");
                    temp.nextToken();
                    ME.MasterAdd(Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), Double.parseDouble(temp.nextToken()), temp.nextToken());
                    return "Successfully added";
                }
                this.ClostIt();
                return "Bad request"; //bad request
        }
        public void ClostIt() {
                try {
                    is.close();
                       os.close();
                        _socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

        }
}

这是服务器部分。它使用SocketFactory类,但主要是它只是在开始时创建一个套接字。在主程序中我调用新的网络(PORT,BACKLOG,InetAddress.getByName(host));

2 个答案:

答案 0 :(得分:1)

我猜你的服务器程序中没有循环,而是这样:

public static void main( String args[] ) {
 ServerSocket server = new ServerSocket(...);
 Socket con = server.accept();
 //process the client connection ...
 //done, exit!
}

而不是

public static void main( String args[] ) {
 ServerSocket server = new ServerSocket(...);
 Socket con = null;
 while( condition /* e.g. shutdown server message received */ ) {
   con = server.accept();
   //process the client connection ...
   //then keep waiting for the next request
 }
 //done, exit!
}

请记住,上面的示例一次只处理一个客户端!您将需要进入多线程来处理同时发生的客户端。

答案 1 :(得分:0)

这是多线程服务器的良好入门者

http://www.kieser.net/linux/java_server.html

标记