连接2仿真实例在Android中实例、Android

2023-09-12 21:32:17 作者:一曲一场叹

我想创建一个服务器,并在2仿真器客户端以写入和读取数据。 我写$ C $下服务器:

I want to create a Server and a Client in 2 Emulator to write and read data. I write code for 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...");
     }


    }

和code客户端

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();
    }

   }
  });
    }
}

我成立了一个重定向:

I set up a redirection :

telnet localhost 5554
redir add tcp:4445:4444

但它没有连接....请帮助我。我AP preciate吧。

But it's not connecting....Please help me. I appreciate it.

推荐答案

我的成功与此一段时间后。我没有在所有10.0.2.15的服务器或客户端的任何引用。我打开服务器套接字不同,曾在一个单独的线程来处理通讯科。我跑模拟器5554和客户端服务器上的5556。

I had success with this after a while. I didn't make any reference at all to 10.0.2.15 in either the server or client. I opened the server socket differently and had the comms handled in a separate thread. I ran the server on emulator 5554 and the client on 5556.

我的服务器code,监听6000

My server code, listening on 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();
            }
         }
      }
   }
}

我重定向相似,你的端口

I redirected ports similar to you

telnet localhost 5554
redir add tcp:5000:6000

我的客户code establshing在端口5000连接:

My client code establshing connection on port 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撰写的消息和一个按钮来发送它。

The server has one TextView to receive the message, the client has one EditText to compose the message in and a button to send it.

 
精彩推荐
图片推荐