首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用异步任务的android socket客户端pc服务器

问使用异步任务的android socket客户端pc服务器
EN

Stack Overflow用户
提问于 2015-01-15 21:21:09
回答 1查看 2.3K关注 0票数 1

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

Android客户端:

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

Pc服务器:

代码语言:javascript
复制
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中,我刚刚添加了

代码语言:javascript
复制
<uses-permission android:name="android.permission.INTERNET"/>

如果我在服务器控制台中从pc启动客户端,我看到设备已连接,但在安卓上不能work..why吗?

谢谢

EN

回答 1

Stack Overflow用户

发布于 2015-07-06 10:16:15

最有可能的是android端的ip是错的。使用内网ip,如: 192.168.1.x。这些类型的ip要求您位于同一网络中。我认为您要做的是从网络外部访问服务器,这需要端口转发。

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

https://stackoverflow.com/questions/27964402

复制
相关文章

相似问题

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