每次服务器打开时,客户端都会创建新的套接字对象

时间:2013-08-30 10:38:12

标签: java android sockets client-server

我已经完成了一个套接字编程,客户端驻留在桌面上的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);
            }
    } 

现在点击按钮的时候,输出如下所示

FISRT CLICK

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

1 个答案:

答案 0 :(得分: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();
    }
}

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