簡體   English   中英

在Android中連接2個仿真器實例

[英]Connecting 2 Emulator instances In Android

我想在2 Emulator中創建一個Server和一個Client來寫入和讀取數據。 我為Server編寫代碼:

public class ServerActivity extends Activity {
    /** Called when the activity is first created. */
 private ServerSocket serverSocket = null;
 private TextView tv;
 public static final int SERVERPORT = 4444;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        tv= (TextView) findViewById(R.id.myTextView);
        try {
   Connect();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   tv.setText("Not connected");
   e.printStackTrace();
  }
    }

    public void Connect() throws IOException
    {
     serverSocket = new ServerSocket();
     serverSocket.bind(new InetSocketAddress("10.0.2.15", 4444));
     while(true)
     {
      Socket socket = serverSocket.accept();
      tv.setText("Connected...");
     }


    }

和客戶代碼

public class ClientActivity extends Activity {
    /** Called when the activity is first created. */
 private Button bt;
 private TextView tv;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        bt = (Button) findViewById(R.id.myButton);
        tv = (TextView) findViewById(R.id.myTextView);
        bt.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
    try {
     Socket socket  = new Socket("10.0.2.2", 4445);
    } catch (UnknownHostException e) {
     // TODO Auto-generated catch block
     tv.setText("Error1");
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     tv.setText("Error2");
     e.printStackTrace();
    }

   }
  });
    }
}

我設置了一個重定向:

telnet localhost 5554
redir add tcp:4445:4444

但它沒有連接....請幫助我。 我很感激。

過了一會兒,我成功了。 我沒有在服務器或客戶端對10.0.2.15做任何引用。 我以不同方式打開服務器套接字,並在單獨的線程中處理了通信。 我在模擬器5554上運行服務器,在5556上運行客戶端。

我的服務器代碼,聽6000

public class SocketServer extends Activity {
   ServerSocket ss = null;
   String mClientMsg = "";
   Thread myCommsThread = null;
   protected static final int MSG_ID = 0x1337;
   public static final int SERVERPORT = 6000;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      TextView tv = (TextView) findViewById(R.id.TextView01);
      tv.setText("Nothing from client yet");
      this.myCommsThread = new Thread(new CommsThread());
      this.myCommsThread.start();
   }

   @Override
   protected void onStop() {
      super.onStop();
      try {
         // make sure you close the socket upon exiting
         ss.close();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   Handler myUpdateHandler = new Handler() {
      public void handleMessage(Message msg) {
         switch (msg.what) {
         case MSG_ID:
            TextView tv = (TextView) findViewById(R.id.TextView01);
            tv.setText(mClientMsg);
            break;
         default:
            break;
         }
         super.handleMessage(msg);
      }
   };
   class CommsThread implements Runnable {
      public void run() {
         Socket s = null;
         try {
            ss = new ServerSocket(SERVERPORT );
         } catch (IOException e) {
            e.printStackTrace();
         }
         while (!Thread.currentThread().isInterrupted()) {
            Message m = new Message();
            m.what = MSG_ID;
            try {
               if (s == null)
                  s = ss.accept();
               BufferedReader input = new BufferedReader(
                     new InputStreamReader(s.getInputStream()));
               String st = null;
               st = input.readLine();
               mClientMsg = st;
               myUpdateHandler.sendMessage(m);
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
   }
}

我重定向了類似於你的端口

telnet localhost 5554
redir add tcp:5000:6000

我的客戶端代碼在端口5000上建立連接:

public class SocketClient extends Activity {
   private Button bt;
   private TextView tv;
   private Socket socket;
   private String serverIpAddress = "10.0.2.2";
   // AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
   // PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
   // PORT 6000
   private static final int REDIRECTED_SERVERPORT = 5000;

   @Override
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      bt = (Button) findViewById(R.id.myButton);
      tv = (TextView) findViewById(R.id.myTextView);

      try {
         InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
         socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
      } catch (UnknownHostException e1) {
         e1.printStackTrace();
      } catch (IOException e1) {
         e1.printStackTrace();
      }

      bt.setOnClickListener(new OnClickListener() {

         public void onClick(View v) {
            try {
               EditText et = (EditText) findViewById(R.id.EditText01);
               String str = et.getText().toString();
               PrintWriter out = new PrintWriter(new BufferedWriter(
                     new OutputStreamWriter(socket.getOutputStream())),
                     true);
               out.println(str);
               Log.d("Client", "Client sent message");

            } catch (UnknownHostException e) {
               tv.setText("Error1");
               e.printStackTrace();
            } catch (IOException e) {
               tv.setText("Error2");
               e.printStackTrace();
            } catch (Exception e) {
               tv.setText("Error3");
               e.printStackTrace();
            }
         }
      });
   }
}

服務器有一個TextView來接收消息,客戶端有一個EditText來組成消息,一個按鈕來發送它。

它很棒

您只需添加兩個步驟:1)在AndroidManifest.xml中的應用程序標記外添加INTERNET權限標記

2)由於UI線程的網絡限制,無法使用android> 3

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM