Android简单客户端/服务器套接字

时间:2014-05-24 17:13:34

标签: java android sockets

我目前正在开发一款Android聊天应用程序。 首先,我创建了服务器,然后是android客户端。但由于某种原因,客户端无法连接到服务器。不过,我已经为客户端和服务器指定了相同的端口。

请问你能帮帮我吗?

以下是我服务器的代码:

public class ChatServer {

    private static int port = 8080;

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


        ServerSocket server = new ServerSocket(port); /* start listening on the port */
        System.out.println( "Listening on "+ server );

        Socket client = null;

        while(true) {
            try {
                client = server.accept();
                System.out.println( "Connection from " + client );
                /* start a new thread to handle this client */
                Thread t = new Thread(new ClientConnect(client));
                t.start();
            } catch (IOException e) {

                System.err.println("Accept failed.");
                System.err.println(e);
                System.exit(1);
                server.close();
            }
        }
    }
}

这是客户:

public class MainActivity extends Activity implements OnClickListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     

    EditText nickname = (EditText)findViewById(R.id.nicknameField);
    EditText password = (EditText)findViewById(R.id.passwordField);
    Button signin = (Button) findViewById(R.id.signin);
    Button signup = (Button) findViewById(R.id.signup);



    new Downloader(this).execute(8080);


}

和Asynctask类

public class Downloader extends AsyncTask<Integer, Void, Void> {

    private WeakReference<MainActivity> activity;
    private int port;

    public Downloader(MainActivity act){
        super();
        activity = new WeakReference<MainActivity>(act);
    }

    protected Void doInBackground(Integer... params) {
        port = params[0];

        try {
            Socket clientSocket = new Socket("localhost", port);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return null;
    }
}

当我在eclipse上使用调试器时,它会通过行

Socket clientSocket = new Socket("localhost", port);

但之后会转到IOException。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

你可以像在智能手机Android上那样在模拟器上访问Android的属性,并查看你要去的IP。

但是,如果您仍在使用Eclipse,我建议您更改为Android Studio,但我认为您会遇到SDK问题,您必须明白这一点,但除此之外没有任何问题。