写入localhost端口并从同一端口读取的Android应用程序

时间:2015-02-18 15:50:23

标签: android sockets bufferedreader bufferedwriter

为了好玩,我尝试编写一个可以写入手机端口并从同一端口读取的应用程序。我创建了两个套接字,并为另一个创建了一个编写器和一个读者。我只是希望读者告诉我它收到了作者的消息,但我无法让它发挥作用。我的方法有明显的缺陷吗? 作者只需每5秒写一次当前时间。

package com.example.service1;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

    public static final String TAG = "com.example.service1.MyService";

    Socket mSocket;
    Socket mSocket2;
    ServerSocket mServerSocket;
    BufferedWriter mBufWriter;
    BufferedReader mBufReader;
    Handler mHandler;
    Timer mTimer;

    @Override 
    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onCreate() {

        Toast.makeText(this, "MyService Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");

        try {

            new CreateSocketTask().execute();

            if(mTimer != null) {

                mTimer.cancel();

            } else {

                mTimer = new Timer();
            }

            mHandler = new Handler();

            mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 1000, 5000);

            new ListenSocketTask().execute();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    private class ListenSocketTask extends AsyncTask<URL, Integer, Long> {
         protected Long doInBackground(URL... urls) {
             try {

                while (true) {
                    Log.d(TAG, "Listening!");
                    if (mSocket2!=null && mBufReader!=null) {
                        while (mSocket2.isConnected()) {
                            Log.d(TAG, "Listening and not null!");
                            final String msg = mBufReader.readLine();
                            Log.d(TAG, msg);
                        }
                    }
                }

            } catch (Exception e) {

                Log.d(TAG, "Exception while listening!");
            }

             return 0L;
         }

         protected void onProgressUpdate(Integer... progress) {
             //setProgressPercent(progress[0]);
         }

         protected void onPostExecute(Long result) {
             //showDialog("Downloaded " + result + " bytes");
         }
     }
    class TimeDisplayTimerTask extends TimerTask {

        @Override
        public void run() {

            mHandler.post(new Runnable() {

                @Override
                public void run() {

                    try {
                        Toast.makeText(getApplicationContext(), mServerSocket.getLocalPort() + " " + getDateTime(), Toast.LENGTH_SHORT).show();
                        mBufWriter.write(getDateTime() + "\n");
                        mBufWriter.flush();
                        Log.d(TAG, "Flushed writer");
                    } catch (Exception e) {
                        Log.d(TAG, "Exception in timer task");
                    }
                }

            });
        }

        private String getDateTime() {
            // get date time in custom format
            SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
            return sdf.format(new Date());
        }

    }

    private class CreateSocketTask extends AsyncTask<URL, Integer, Long> {
         protected Long doInBackground(URL... urls) {
             try {

                // InetAddress serverAddr = InetAddress.getByName("localhost");
                // mSocket = new Socket("localhost", 4444);

                mServerSocket = new ServerSocket(34107);

                mSocket = new Socket(InetAddress.getByName("localhost"), 34107);
                mSocket2 = new Socket(InetAddress.getByName("localhost"), 34107);

                mBufWriter = new BufferedWriter(new PrintWriter(mSocket.getOutputStream()));
                mBufReader = new BufferedReader(new InputStreamReader(mSocket2.getInputStream()));
                // Toast.makeText(MyService.this, "Port: " + mServerSocket.getLocalPort(), Toast.LENGTH_LONG).show();

                return (long)(mServerSocket.getLocalPort());

             } catch (Exception e) {

                e.printStackTrace();
            }

             return 0L;
         }

         protected void onProgressUpdate(Integer... progress) {
             //setProgressPercent(progress[0]);
         }

         protected void onPostExecute(Long result) {
             //showDialog("Downloaded " + result + " bytes");
         }
     }

    @Override
    public void onStart(Intent intent, int startId) {

        Toast.makeText(this, "MyService Started", Toast.LENGTH_LONG).show();

        Log.d(TAG, "onStart");
    }

    @Override
    public void onDestroy() {

        Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();

        Log.d(TAG, "onDestroy");

        try {

            mServerSocket.close();
            mSocket.close();
            mSocket2.close();
            mBufWriter.close();
            mBufReader.close();

        } catch (Exception e) {

        }
    }
}

日志产生以下内容:

02-18 16:54:13.142: D/libEGL(28003): loaded /system/lib/egl/libEGL_mali.so
02-18 16:54:13.192: D/libEGL(28003): loaded /system/lib/egl/libGLESv1_CM_mali.so
02-18 16:54:13.202: D/libEGL(28003): loaded /system/lib/egl/libGLESv2_mali.so
02-18 16:54:13.302: D/OpenGLRenderer(28003): Enabling debug mode 0
02-18 16:54:17.246: D/com.example.service1.MyService(28003): onCreate
02-18 16:54:17.266: D/com.example.service1.MyService(28003): onStart
02-18 16:54:17.326: D/com.example.service1.MyService(28003): Listening!
02-18 16:54:17.326: D/com.example.service1.MyService(28003): Listening and not null!
02-18 16:54:17.406: D/dalvikvm(28003): GC_CONCURRENT freed 146K, 10% free 9568K/10567K, paused 28ms+5ms, total 115ms
02-18 16:54:18.297: D/com.example.service1.MyService(28003): Flushed writer
02-18 16:54:23.272: D/com.example.service1.MyService(28003): Flushed writer
02-18 16:54:28.266: D/com.example.service1.MyService(28003): Flushed writer
02-18 16:54:33.271: D/com.example.service1.MyService(28003): Flushed writer

0 个答案:

没有答案