【问题标题】:Connecting 2 Emulator instances In Android在 Android 中连接 2 个模拟器实例
【发布时间】:2011-01-13 18:39:54
【问题描述】:

我想在 2 Emulator 中创建一个服务器和一个客户端来写入和读取数据。 我为服务器编写代码:

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

但它没有连接....请帮助我。我很感激。

【问题讨论】:

  • 我从来没有找到一种方法来做到这一点。祝你好运。
  • @Falmarri:NickT 发布的内容很棒!

标签: android


【解决方案1】:

一段时间后我成功了。我根本没有在服务器或客户端中对 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来编写消息和一个按钮来发送消息。

【讨论】:

  • 感谢 NickT,效果很好。希望我能接受你的回答。 =P
  • 我试图在我的机器上运行你的代码,但它在客户端给我错误3,你能帮我吗?
  • 太久以前我不记得对不起。在那个 catch 块中放一个断点,看看它是什么类型的异常。
  • socket = new Socket(serverAddr, REDIRECTED_SERVERPORT); 在主线程异常上引发网络。
【解决方案2】:

效果很好

您只需要添加两个步骤: 1) 在AndroidManifest.xml中应用标签外添加INTERNET权限标签

2) 由于 UI 线程的网络限制,不适用于 android > 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多