开发者

Android Application cannot open socket to connect Server

I am developing an Android Application, and application needs to connect server. This is the client code. 79.123.176.59 is the server's IP address. Application and the server are connected to same network. When I execute my application, it never opens a socket. So it cannot connect to server.

When I execute client code seperate from the application, it just works fine!

What is the problem ? Do you have any suggestions ?

Thank you!

int port=8080;
   Socket s;
   String msg="";
   String err="error";
   try{
       Log.d("Client","Socket");
       s=new Socket("79.123.176.59",port);
       Log.d("Client","Socket opened");
       OutputStreamWriter osw=new OutputStreamWriter(s.getOutputStream());
       PrintWriter pw=new PrintWriter开发者_高级运维(osw);
       BufferedReader br1=new BufferedReader(new InputStreamReader(s.getInputStream()));
       Log.d("Client","Streams");
       pw.println(latitude + " " + longitude );
       Log.d("Client","String send");
       pw.flush();
       msg=br1.readLine();
       return msg;
   }
   catch ( Exception e )
   {
       return err;
   }


You are not closing the socket neither the streams. So maybe you cannot connect because your device is blocked by a socket you opened before. Try to put this after your catch (and dont do return inside try/catch)

finally {

        pw.close();
        br1.close();
        s.close();
}


TCP SOCKET on Android You can follow this thread and the code is also available there.


The Socket constructor does not take a string, I don't get how that even compiles?

Try this

s=new Socket(new InetAddress.getByName("79.123.176.59"),port)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜