android使用socket於本地PC進行通訊的問題

來源:互聯網
上載者:User

1.自己首先建立個java project.用它做為伺服器端的程式,代碼如下:

package com.server;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Myserver {
 public static void main(String[] args) {
  try {
   ServerSocket server=new ServerSocket(5000);
   while(true){
    Socket client=server.accept();
    OutputStream out=client.getOutputStream();
    String msg="Hello android";
    out.write(msg.getBytes());
    client.close();
   
   }
  } catch (IOException e) {
  
   e.printStackTrace();
  }
 }

}

 

2.建立android用戶端程式,代碼如下:

package com.android;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SocketTestActivity extends Activity {
    private TextView myTextView;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        myTextView=(TextView)findViewById(R.id.msgTextView01);
        myTextView.setText("dd");
        try {
        

   Socket socket=new Socket("127.0.0.1",5000);
     myTextView.setText("ff");
   InputStream in=socket.getInputStream();
   byte[]buffer=new byte[in.available()];
   in.read(buffer);
   String msg=new String(buffer);
   System.out.println(msg);
  } catch (UnknownHostException e) {
 
   e.printStackTrace();
  } catch (IOException e) {
    myTextView.setText("ee");
   e.printStackTrace();
  }
    }
}

3.然後運行java project中的程式,查看連接埠,已經等待監聽。

4.運行android應用程式在用戶端,報錯,無法建立socket串連,錯誤資訊是java.net.PlainSocketImpl.connect,這說明沒有串連成功,因為IP地址或連接埠號碼錯誤。

花了好長時間在網上查看原因,有說把ip:127.0.0.1改成10.0.2.0的,結果不行,10.0.2.2是模擬器的IP,相當於本地的127.0.0.1.是android的路由器給每個模擬器分配的IP地址。

有進入cmd,輸入ipconfig,直接使用裡面的IP的,也不行的。

後來進行連接埠的映射,使用命令telnet localhost 5554,

diret tcp:5000:6000,也不行,後來發現這是在兩天模擬器上進行請求轉寄是需要配置的資訊,不能完成模擬器和PC的通訊的。

最後嘗試將連接埠號碼寫成模擬器的連接埠號碼,我5554或5556,還是不行的。

這都要害死我了。

這才是王道,這才是正解:

 

在android的官方網站上是這麼寫的:本網串連受限。每個模擬器運行在背景虛擬路由上,模擬器不能接入物理路由器。於模擬器互動資訊可能被本地的防火牆阻塞,或者被你串連的防火牆阻塞。也就是說兩個模擬器直接可以通過請求轉寄實現通訊,模擬器和PC不能通訊。

 

我的解決方案:用真機進行測試,通過了。沒有真機的,那就沒辦法了。希望那些還沒解決的人不要浪費時間了。期待Google能快點解決這個問題。 


摘自 燕龍安的專欄 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.