首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >通过互联网连接2台android设备

通过互联网连接2台android设备
EN

Stack Overflow用户
提问于 2015-03-08 05:17:53
回答 1查看 736关注 0票数 0

我正在尝试连接两个android设备(中间没有服务器,直接像点对点一样),它们连接到互联网(它们相距很远)并发送消息。

我认为它就像普通的套接字编程,并通过IP连接,似乎不是。

到目前为止,我所做的是:

我已经创建了2个android项目,服务器(接收方)和客户端(发送方)

在两个独立的设备中运行

这两个设备都已连接到互联网

找到在中运行服务器应用程序的设备的IP (使用whatismyip.com)并在客户端应用程序代码中使用它

但是,当我想要从客户端向服务器发送文本时,客户端打印Error3时会发生异常

这是我的代码: server:

代码语言:javascript
复制
   public class MainActivity 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.activity_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();
            }
        }
    }
    }
}

客户端(Error3):

代码语言:javascript
复制
   public class MainActivity extends Activity {

   private Button bt;
   private TextView tv;
   private Socket socket;
   private String serverIpAddress = "5.114.22.118";
   // 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 = 80;

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

      new Thread(new ClientThread()).start();

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

   class ClientThread implements Runnable {

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

}
EN

回答 1

Stack Overflow用户

发布于 2015-03-08 06:22:43

我认为这将是更合适的评论,但我没有足够的声誉来评论,所以我提供它作为答案。您的服务器是否连接到路由器?whatismyip.com返回路由器的IP地址,而不是设备的IP地址。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28920115

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档