java - 服务器与客户端通信问题

标签 java sockets tcp

我正在使用 Java 上的客户端-服务器程序示例。我遇到了这样的问题: 我使用 8080 端口和本地主机启动服务器,然后启动客户端并发出请求。请求完成后,两个程序都会关闭套接字,因此我无法重复我的操作。如何使用同一个客户端和同一个服务器发出多个请求?

    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 类,但主要只是在开始时创建一个套接字。在主程序中,我调用 new Network(PORT, BACKLOG, InetAddress.getByName(host));

最佳答案

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

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!
}

请记住,上述示例一次仅处理一个客户端!您将需要进入多线程来处理并发客户端。

关于java - 服务器与客户端通信问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5792610/

相关文章:

java - Java EE/JBoss AS 6 中的预身份验证用户

JavaFX 应用程序线程 - 使用 Gluon Ignite 依赖注入(inject)时

java - 静态方法中的 SharedPreferences - 尽管传递了默认值,但 Lint 警告 "might be null"?

c++ - toLocal8bit 通过 TCP 发送

Linux TCP : packet segmentation?

java - 如何访问正在运行的 servlet 过滤器?

c - 通过 TCP 套接字发送 unicode,字节顺序如何

java - 如何在 Java 代码中接收 Simulink 常量值?

perl tcp 客户端不显示传入数据

c - unix 域套接字的 tcp_nodelay 设置