开发者

Android Client not able to connect to a server

开发者 https://www.devze.com 2023-03-30 10:30 出处:网络
I have a server running on my computer and I would like my android app to connect to it. In other words, I would like to write an Android client that establishes a TCP connection, writessomething to t

I have a server running on my computer and I would like my android app to connect to it. In other words, I would like to write an Android client that establishes a TCP connection, writes something to the server and listens for responses from the server. Below is the client code:

public class Text extends A开发者_如何学Pythonctivity 
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        String fromServer, ToServer, filename;
        BufferedReader inFromServer;
        PrintWriter outToServer;
        Socket clientSocket;

        super.onCreate(savedInstanceState);

        try 
        {
        clientSocket = new Socket("86.36.32.251", 8000);
        outToServer  = new PrintWriter(clientSocket.getOutputStream(),true);
        inFromServer = new BufferedReader(
                   new InputStreamReader(clientSocket.getInputStream()));

        filename = "profile.txt";
        ToServer = Reader.readFileAsString(filename);
        ToServer += "\n";

        outToServer.println(ToServer);

        while((fromServer = inFromServer.readLine()) != null)
        {
            TextView tv = new TextView(this);
            tv.setText(fromServer);
            setContentView(tv);
        }

        inFromServer.close();
    }
    catch(UnknownHostException e)
    {
        e.printStackTrace();
    }
    catch (IOException e) 
    {
        e.printStackTrace();
    }
}

}

However, when I run my application, the application does not establish a TCP connection to my server. I don't know what the problem might be. I have gone through the following link http://thinkandroid.wordpress.com/2010/03/27/incorporating-socket-programming-into-your-applications/ which discusses the client-side of socket programming and I feel I have all the main steps in my client. Could someone please help me resolving the issue. Thanks


Please make sure you've added the internet permission. If you did, run this on a real device. If it still doesn't work, paste the logcat.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号