0

我已经使用驻留在android上的客户端和驻留在桌面上的服务器进行了套接字编程......每当服务器关闭时,我们知道客户端失去了连接......所以它会经历一个循环,直到它连接到服务器.......

这里的问题是在下面的代码

tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);

在连接丢失的情况下的while循环中......但是当连接上它再次创建一个新对象............

谁能告诉我如何解决这个问题............

在客户端

while(true){
        try {

            tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);

            tabletout = new PrintWriter(tabletclient.getOutputStream());
            in = new Scanner(tabletclient.getInputStream());
            try
            {
                if((line = in.nextLine())!=null)
                {
                    // my task to be done 
                }
            }catch(Exception d){
                System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"+tabletclient.isConnected());

            }
            } catch (UnknownHostException e) {  System.out.println("Entered 2.........");
            } catch (IOException e) {  System.out.println("Entered 3.........");e.printStackTrace();
            }
         }

在服务器端

:
:
       private Set <Socket> TABhs=new HashSet<Socket>();
:
:
        new Thread(new TABServerThread()).start(); // runs in background
:
:
:
 class ServerThread implements Runnable {
        private ServerSocket server;

        @Override
        public void run() {
            try {
                server = new ServerSocket(SERVER_PORT);
                System.out.println("Server Start the server at port " + SERVER_PORT
                        + " and waiting for clients...");
                while (true) {
                    Socket socket = server.accept();
                    System.out.println("Server Accept socket connection: "
                                    + socket.getLocalAddress());
                      new Thread(new ClientHandler(socket)).start();
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

private static PrintWriter out;

    class ClientHandler implements Runnable {

        private Socket clientSocket;

        private Scanner in;

        public ClientHandler(Socket clietSocket) {
            this.clientSocket = clietSocket;
        }

        @Override
        public void run() {
            try {
                out = new PrintWriter(clientSocket.getOutputStream());
                in = new Scanner(clientSocket.getInputStream());
                String line;
                System.out.println("ClientHandlerThread Start communication with : "+ clientSocket.getLocalAddress());
                try{
                while((line = in.nextLine()) != null) {
                    System.out.println("ClientHandlerThread Client says: " + line);
                    String dat[]=line.split("#");
                        String query="insert into table_orders (tableno,kotno, orders,status) values('"+dat[1]+"','"+dat[0]+"','"+dat[2]+"','pending')";
                        try {
                            int i= dbGetDet.insertDetails(query);
                            if(i>0)
                            {
                             fillTable();
                             filtercomboBox();
                             out.print("success");
                             out.flush();
                             for(Socket so:TABhs)
                             {
                                PrintWriter ot = new PrintWriter(so.getOutputStream());
                                ot.println("tableallocation#"+dat[1]);
                                ot.flush();
                             }
                                System.out.println("SENDED 'SUCCESS' TO CLIENT");
                            }
                        } catch (Exception ex) {
                            Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
                        } 
                   // }
                }
                }catch(Exception r){}
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

在服务器的按钮单击

String stat=status_combo.getSelectedItem().toString();
  String tables=tableno_combo.getSelectedItem().toString();
  String kotno=kotno_combo.getSelectedItem().toString();
  if(stat.equals("Processing"))
  {
        try {
            TABhs = new CopyOnWriteArraySet(TABhs);
            int soint=1;
            System.out.println("TABhs Processing--------------------->"+TABhs.size());
            for(Iterator <Socket> it=TABhs.iterator();it.hasNext();)
            { 
                Socket so=it.next();
                System.out.println("SEEE SOCKET Processing"+soint+"----->"+so.isClosed());
                PrintWriter ot = new PrintWriter(so.getOutputStream());
                ot.println("tableupdate#"+tables+"#"+kotno+"#processing");
                ot.flush();
                JOptionPane.showMessageDialog(rootPane, "<html><body>Table Kot Status Changed to <b>Processing</b></body></html>");
                soint++;
            }

            System.out.println("TABhs Processing--------------------->"+TABhs.size());
            }
            catch (Exception ex) {
            Logger.getLogger(MYClientclass.class.getName()).log(Level.SEVERE, null, ex);
            }
    } 

现在每次单击按钮时,输出如下所示

第一次点击

SEEE SOCKET Ready 1----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 2----->false
TABhs--------------------->2

第二次点击

SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 3----->false
TABhs--------------------->4

第四次点击

SEEE SOCKET Ready 1----->false
SEEE SOCKET Ready 2----->false
SEEE SOCKET Ready 3----->false
Server Accept socket connection: /192.168.1.74
SEEE SOCKET Ready 4----->false
TABhs--------------------->5
4

1 回答 1

0

我认为问题出在客户端,您读取了一行,然后创建了一个新连接。我认为您必须继续阅读套接字,直到它关闭或发生错误。

例如:

while (true)
{
    tabletclient = null;
    int loop = 0;
    // loop until a connection is established
    while (tabletclient == null)
    {
        try
        {
            tabletclient = new Socket(SERVER_IP, TAB_SERVER_PORT);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            // set the value to quit when no connection could be established
            if (loop++ > 100)
                return;
        }
    }

    try
    {
        tabletout = new PrintWriter(tabletclient.getOutputStream());
        in = new Scanner(tabletclient.getInputStream());
        // read the socket until it's closed or an error occurs
        try
        {
            while ((line = in.nextLine()) != null)
            {
                // my task to be done
            }

        }
        catch (Exception d)
        {
            System.out.println("Connection from server has lost.........tabletclient.isConnected()----->"
                            + tabletclient.isConnected());
        }
        tabletsocket.close();
    }
    catch (UnknownHostException e)
    {
        System.out.println("Entered 2.........");
    }
    catch (IOException e)
    {
        System.out.println("Entered 3.........");
        e.printStackTrace();
    }
}

此外,从服务器到客户端的传输完成后,您必须关闭服务器端。

于 2013-08-30T14:31:45.160 回答