如何编写将在已创建的后台监听的客户端套接字?

时间:2013-04-20 21:23:22

标签: java android sockets client

首先,我是相当新的我有服务器/客户端套接字在运行,服务器正在发送/接收数据,但我的客户端此刻只是在try / catch块中发送数据,我需要写一个另一种捕获传入数据的方法? 并将它保持在原来的try / ctach *之外

任何帮助都会很棒

public void onClick(View v)
         {
             setMyIp(ipaddress.getText().toString());
            // myComs.sending_data(getMyIp() , "Got connected");
            try
             {
                 InetAddress inet = InetAddress.getByName(getMyIp());
                 Socket s = new Socket(inet, 2000);
                 OutputStream o = s.getOutputStream();
                 PrintWriter p = new PrintWriter(o);
                 InputStream in = s.getInputStream();


                 p.println("You are connected");
                 p.flush();

                 readContacts();
                 //inboxConversations();
                 //outboxConversations();
                 readSms();


             }
             catch (UnknownHostException e) 
             {
                ipaddress.setText("Unknown host");
                   e.printStackTrace();
             }
            catch (IOException e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

         }


     });

这是我的代码,我需要在按钮之外创建一个单独的监听器

谢谢


2 个答案:

答案 0 :(得分:1)

你必须在循环中保持套接字不断监听任何数据写入。当然,在单独的线程/进程上执行此操作。实际上,在我看来,服务器端和客户端都应该是一个单独的线程。你可以查找java NIO,但是这里有一些代码只需要你开始,因为android有一个类可以在后台执行操作并更新主UI之后称为ASYNCHTASK。你可以用其他方式产生一个线程,当然只是向你展示一个方便的方法: (注意我没有运行这个我只是写它如何做它所以它把它作为伪代码)

class ClientTask extends AsyncTask<Void, Void, Void> // or whatever you want to pass in
{

        public static String ip = "10.0.2.1";
        public static int port = 5061;
        Socket socket;
        public DataInputStream dis;
        public DataOutputStream dos;
        public String message;

        @Override
        protected Void doInBackground(Void... params) {


/* set up our socket and open a stream to read */

                 try {
                socket = new Socket(ip, port);
        dis = new BufferedReader(new InputStreamReader(socket.getInputStream()));           

            } catch (Exception e) {
                Log.i("AsyncTank class", "Socket has some trouble opening");
            }

/*heres the stuff your looking for to listen to a socket all day long*/

while(socket.isConnected()){
                String mymessage=dis.readLine(); //readline blocks
/* do something with your message */    
publishProgress(mymessage); //publishes update to main UI thread            
                        }
                }

            }
            return null;
        }



@Override
    protected void onProgressUpdate(String... messages) {

     Toast.makeText(this, messages,Toast.LENGTH_LONG).show(); //announce updates on incoming socket

}


}

--------如果您因为任何原因关闭套接字后不需要更新主UI,只需执行相同的操作,但使用runnable或Thread类来创建和监听。

答案 1 :(得分:0)

如果你需要一个客户端作为接收者,你已经为这个异步行为运行了一个线程,否则如果你在主线程上执行它就会冻结你的应用程序。

所以做以下事情

在客户端的main方法中启动接收器线程

Thread receiver_thread=new Thread(new Reciever());
reciever_thread.start();

这是接收器类

public class Receiver implements Runnable  
{
    public void run()  
    {
        While(true)
        {
            //check here if there is some data in your input stream so what              
               //you receive when server sends something to you

           //so that's it here  do your work with the incoming data
           //suggestion make an inner class to your main ui class so that data that comes here can be printed to those ui components.
         }
      }
}

希望它可以帮到你