【问题标题】:how to get simple android client and pc server get working如何让简单的 android 客户端和 pc 服务器开始工作
【发布时间】:2011-01-31 12:45:16
【问题描述】:

我的电脑上有一个简单的服务器,我的 htc 上有一个简单的客户端,希望运行 android 2.2。

服务器和客户端都使用相同的端口。我将服务器 ip 硬编码到客户端代码中。当我尝试通过 android 上的客户端连接到正在运行的服务器时,客户端会抛出此异常:

IOException ...: java.net.SocketException: The operation timed out.

以下是部分客户端和服务器代码:

客户端代码

  InetAddress addr;
  Socket socket = null;

  byte [] ipAddress = new byte[] {(byte)82,(byte)168,(byte)175,(byte)141};

  try{

   addr = InetAddress.getByAddress(ipAddress);

   socket = new Socket(addr, 1234);
   System.out.println("socket = "+socket);

   BufferedReader in = new BufferedReader(
            new InputStreamReader(
             socket.getInputStream()));

   PrintWriter out = new PrintWriter(
            new BufferedWriter(
             new OutputStreamWriter(socket.getOutputStream())),true);

        out.println("hello");
        socket.close();
  } catch (UnknownHostException e) {
   System.out.println("UnknownHostException ...: "+e);
  } catch (IOException e) {
   System.out.println("IOException ...: "+e);
  }

,

服务器代码

    ServerSocket ss = new ServerSocket(PORT);
  System.out.println("Started:"+ss);

  try{
   //block until a connection occures
   Socket socket = ss.accept();

   try{
    System.out.println("Conncetion accepted:"+socket);
    InputStream IS = socket.getInputStream();
    InputStreamReader ISR = new InputStreamReader(IS);
    BufferedReader in = new BufferedReader(ISR);

    OutputStream OS = socket.getOutputStream();
    OutputStreamWriter OSR= new OutputStreamWriter(OS);
    BufferedWriter BW = new BufferedWriter(OSR);
    //output automatically flushed by PrintWriter
    PrintWriter out = new PrintWriter(BW,true);

    while(true){
     String str = in.readLine();
     System.out.println("Client: "+str);
     out.println("hi");
    }
   }finally{
    System.out.println("Closing...");
    socket.close();
   }
  }finally{
   ss.close();
  }

此代码使用 wifi 但不能通过 3g 工作。

欢迎任何帮助...提前感谢您。

【问题讨论】:

    标签: android client timeoutexception


    【解决方案1】:

    您可能使用路由器/wifi 接入点连接到互联网?

    如果您的路由器使用NAT protocol,那么Internet 上的任何设备都无法打开与您PC 的连接。 NAT 只允许 PC 打开与互联网的连接,反之亦然。

    因此,当您的手机在 wifi 上时,它可以连接到 PC,因为它们都在同一个网络上,并且不使用 NAT。当您的手机使用 3g 网络时,因此在您的手机和 PC 之间存在 NAT。

    解决方案:

    在您的路由器上启用端口转发,然后将您的应用程序连接到路由器的 IP,路由器的 IP 将把此连接转发到您的 PC。

    【讨论】:

    • 健吾,谢谢您的回复。所以这意味着如果有 NAT 就没有 tcp 连接?或者有解决办法吗?
    • NAT 不允许入站(inet 到 PC)连接。解决方案是端口转发。
    猜你喜欢
    • 2013-02-05
    • 1970-01-01
    • 2014-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多