【问题标题】:android socket client pc server using asynctaskandroid socket客户端pc服务器使用asynctask
【发布时间】:2015-03-13 21:40:58
【问题描述】:

我正在使用 asynctask 在客户端(在我的 android 设备上运行)和服务器(在我的电脑上运行)建立连接。当我启动应用程序时,我必须单击按钮来连接它们,如果客户端已连接但未出现,我的服务器 pc 程序应在控制台设备中显示我;我的安卓客户端没有连接到我的电脑服务器。

安卓客户端:

 public class MainActivity extends ActionBarActivity {

    Button send;
    EditText txt;
    TextView testo;
    String response = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        send = (Button) findViewById(R.id.send);
        //txt = (EditText) findViewById(R.id.editText);
        testo = (TextView) findViewById(R.id.textView1);
    }


    class AddStringTask extends AsyncTask<Void, String, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected Void doInBackground(Void... unused) { 

            try {
                Socket socketClient = new Socket("10.10.0.151",4321); //ipaddress of my pc server
            } catch (UnknownHostException e) {
                e.printStackTrace();
                response = e.toString();
            } catch (IOException e) {
                e.printStackTrace();
                response = e.toString();
            }
            testo.setText(response);
            return (null);
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void onProgressUpdate(String... item) {

        }

        @Override
        protected void onPostExecute(Void unused) {
            testo.setText(response);
        }
    }

    public void buttonClick(View v){
        new AddStringTask().execute();
    }
}

电脑服务器:

public class Server {

public static Socket connection;

public static void main(String[] args) throws IOException {

    System.out.println("Starting server on port number: 4321...");
    ServerSocket server = new ServerSocket(4321);

    while(true){
        System.out.println("Waiting for clients...");
        connection = server.accept();
        System.out.println("Connected to: "+connection.getInetAddress().getHostAddress());
        connection.close();

    }
}

}

在我刚刚添加的 AndroidManifest.xml 中

<uses-permission android:name="android.permission.INTERNET"/>

如果我在服务器控制台中从 pc 启动客户端,我会看到设备已连接,但在 android 上不起作用..为什么?

谢谢

【问题讨论】:

  • 确保您的服务器 IP 正确,并且您已关闭 PC 上的防火墙(有时它不允许连接)

标签: android sockets android-asynctask


【解决方案1】:

很可能是android端的ip不对。使用私有 IP 例如:192.168.1.x。这些类型的 ip 要求您在同一个网络上。我认为您要做的是从网络外部访问服务器,这需要端口 fkrwarding。

【讨论】:

    猜你喜欢
    • 2014-02-19
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2012-06-27
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    • 2018-10-14
    相关资源
    最近更新 更多