如何通过套接字重复发送值

时间:2016-10-29 13:49:37

标签: android sockets client-server

我有这个客户端和服务器通信程序。我从Android-er网站上得到了这个想法。

当客户按下连接按钮时,此代码会发送一个随机数,我希望在客户端与服务器连接时每五分钟发送一个新的随机数。

客户代码:

public class MainActivity extends AppCompatActivity {
    TextView textResponse;
    EditText editTextAddress, editTextPort;
    Button buttonConnect, buttonClear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        editTextAddress = (EditText)findViewById(R.id.address);
        editTextPort = (EditText)findViewById(R.id.port);
        buttonConnect = (Button)findViewById(R.id.connect);
        buttonClear = (Button)findViewById(R.id.clear);
        textResponse = (TextView)findViewById(R.id.response);

        buttonConnect.setOnClickListener(buttonConnectOnClickListener);

        buttonClear.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                textResponse.setText("");
            }});
    }

    View.OnClickListener buttonConnectOnClickListener = new View.OnClickListener(){

                @Override
                public void onClick(View arg0) {
                    MyClientTask myClientTask = new MyClientTask(
                            editTextAddress.getText().toString(),
                            Integer.parseInt(editTextPort.getText().toString()));
                    myClientTask.execute();
                }};

    public class MyClientTask extends AsyncTask<Void, Void, Void> {

        String dstAddress;
        int dstPort;
        String response = "";

        MyClientTask(String addr, int port){
            dstAddress = addr;
            dstPort = port;
        }

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

            Socket socket = null;

            try {
                socket = new Socket(dstAddress, dstPort);

                ByteArrayOutputStream byteArrayOutputStream =
                        new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];

                int bytesRead;
                InputStream inputStream = socket.getInputStream();

    /*
     * notice:
     * inputStream.read() will block if no data return
     */
                while ((bytesRead = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "UnknownHostException: " + e.toString();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                response = "IOException: " + e.toString();
            }finally{
                if(socket != null){
                    try {
                        socket.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            textResponse.setText(response);
            super.onPostExecute(result);
        }

    }
}

这是服务器的代码:

public class MainActivity extends AppCompatActivity {
    TextView info, infoip, msg, randGen;
    String message = "";
    ServerSocket serverSocket;
    String vRand="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        info = (TextView) findViewById(R.id.info);
        infoip = (TextView) findViewById(R.id.infoip);
        msg = (TextView) findViewById(R.id.msg);
        randGen= (TextView)findViewById(R.id.viewRand);

        infoip.setText(getIpAddress());

        Thread socketServerThread = new Thread(new SocketServerThread());
        socketServerThread.start();
    }
    public String rGenerate() {
        Random rand= new Random();
        int number= rand.nextInt(500-251)+251;
        vRand = String.valueOf(number);
        //randGen.setText(vRand);
        return vRand;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    private class SocketServerThread extends Thread {

        static final int SocketServerPORT = 8080;
        int count = 0;

        @Override
        public void run() {
            try {
                serverSocket = new ServerSocket(SocketServerPORT);
                MainActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        info.setText("I'm waiting here: "
                                + serverSocket.getLocalPort());
                    }
                });

                while (true) {
                    Socket socket = serverSocket.accept();
                    count++;
                    message += "#" + count + " from " + socket.getInetAddress()
                            + ":" + socket.getPort() + "\n";

                    MainActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            msg.setText(message);
                        }
                    });

                    SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
                            socket, count);
                    socketServerReplyThread.run();

                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private class SocketServerReplyThread extends Thread {

        private Socket hostThreadSocket;
        int cnt;

        SocketServerReplyThread(Socket socket, int c) {
            hostThreadSocket = socket;
            cnt = c;
        }

        @Override
        public void run() {
            OutputStream outputStream;
            String num =rGenerate();

            try {
                outputStream = hostThreadSocket.getOutputStream();
                PrintStream printStream = new PrintStream(outputStream);
                printStream.print(num);
                printStream.close();

                message += num + "\n";

                MainActivity.this.runOnUiThread(new Runnable() {

                    @Override
                    public void run() {
                        msg.setText(message);
                    }
                });

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                message += "Something wrong! " + e.toString() + "\n";
            }

            MainActivity.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    msg.setText(message);
                }
            });
        }

    }

    private String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                    .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                        .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                        .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();

                    if (inetAddress.isSiteLocalAddress()) {
                        ip += "SiteLocalAddress: "
                                + inetAddress.getHostAddress() + "\n";
                    }

                }

            }

        } catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            ip += "Something Wrong! " + e.toString() + "\n";
        }

        return ip;
    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用处理程序在特定时间段内执行某些操作。试试这个

Handler customHandler = new android.os.Handler();
static final int SOCKET_VERIFY_TIME = 5000;  //milliseconds

@Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   ...
   customHandler.postDelayed(updateTimerThread, SOCKET_VERIFY_TIME);
   ...
   }

private Runnable updateTimerThread = new Runnable() {
     public void run()
     {
         if(socket != null) {
             if(socket.connected()) {
                socket.emit("eventNumber", randNumber);
             }

         }
         customHandler.postDelayed(this, SOCKET_VERIFY_TIME);
     }
 };

如果您想要停止更新,请使用此

customHandler.removeCallbacks(updateTimerThread);

在您的客户端

public class MainActivity extends AppCompatActivity {
TextView textResponse;
EditText editTextAddress, editTextPort;
Button buttonConnect, buttonClear;
Handler customHandler = new android.os.Handler();
static final int SOCKET_VERIFY_TIME = 5000;  //milliseconds


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    editTextAddress = (EditText)findViewById(R.id.address);
    editTextPort = (EditText)findViewById(R.id.port);
    buttonConnect = (Button)findViewById(R.id.connect);
    buttonClear = (Button)findViewById(R.id.clear);
    textResponse = (TextView)findViewById(R.id.response);

    buttonConnect.setOnClickListener(buttonConnectOnClickListener);

    buttonClear.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            textResponse.setText("");
        }});


      /***** Events Socket  ***********/
      socket = IO.socket(new URI(URL_SERVER));
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                yourActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        // Socket is connect. Do something here 
                        /******************* Set Handler delay ******************/
                        customHandler.postDelayed(updateTimerThread, SOCKET_VERIFY_TIME);
                        /************************************************/

                    }
                });
            }
        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
            @Override
            public void call(final Object... args) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        // Socket is disconnect. Do something here 

                        customHandler.removeCallbacks(updateTimerThread); // stop handler updates

                    }
                });
            }
        })
}

View.OnClickListener buttonConnectOnClickListener = new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                MyClientTask myClientTask = new MyClientTask(
                        editTextAddress.getText().toString(),
                        Integer.parseInt(editTextPort.getText().toString()));
                myClientTask.execute();
            }};

  private Runnable updateTimerThread = new Runnable() {
       public void run()
       {
           if(socket != null) {
               if(socket.connected()) {
                  socket.emit("eventNumber", randNumber);
               }

           }
           customHandler.postDelayed(this, SOCKET_VERIFY_TIME);
       }
   };


public class MyClientTask extends AsyncTask<Void, Void, Void> {

    String dstAddress;
    int dstPort;
    String response = "";

    MyClientTask(String addr, int port){
        dstAddress = addr;
        dstPort = port;
    }

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

        Socket socket = null;

        try {
            socket = new Socket(dstAddress, dstPort);

            ByteArrayOutputStream byteArrayOutputStream =
                    new ByteArrayOutputStream(1024);
            byte[] buffer = new byte[1024];

            int bytesRead;
            InputStream inputStream = socket.getInputStream();

/*
 * notice:
 * inputStream.read() will block if no data return
 */
            while ((bytesRead = inputStream.read(buffer)) != -1){
                byteArrayOutputStream.write(buffer, 0, bytesRead);
                response += byteArrayOutputStream.toString("UTF-8");
            }

        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "UnknownHostException: " + e.toString();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = "IOException: " + e.toString();
        }finally{
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        textResponse.setText(response);
        super.onPostExecute(result);
    }

}
}

答案 1 :(得分:0)

您可以使用处理程序以特定延迟执行任务。我假设你知道如何使用套接字发送随机数,所以我不会搞乱套接字代码

Button button = (Button) findViewById(R.id.start_button);
button.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
    handler.postDelayed(new Runnable() {
      @Override
      public void run() {
        sendData();
        handler.postDelayed(this, 15000);
                    }
      }, 15000);

    }
});

private void sendData(){
        new Worker().execute();
}


private class Worker extends AsyncTask<Void, Void, String>{
  private static final String TAG = "Worker";
  @Override
  protected String doInBackground(Void... params) {
    return "Hello There";
  }

  @Override
  protected void onPostExecute(String s) {
    Log.i(TAG, s);
  }
}