本地PC服务器和android模拟器之间的套接字连接

时间:2011-12-16 11:26:35

标签: java android eclipse sockets networking

我遇到了PC(用Java编写的简单服务器)和android模拟器的套接字连接的麻烦。建立连接,服务器发送数据,但是当我尝试在android上读取它时,它总是读取空字符串。以下是我的代码的一些部分:

服务器:

serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.write("Output string");
socket.close();

客户端:

socket = new Socket("10.0.2.2", 8888);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = input.readLine();
Log.i(TAG, s);
socket.close();

我省略了try-catches和log for clearness。根据日志,建立连接,服务器发送数据,但客户端只接收空字符串。我很感激任何帮助。

3 个答案:

答案 0 :(得分:2)

这对我有用......(此代码仅用于从服务器和客户端的套接字写入和读取数据)

服务器

  BufferedOutputStream bos = new BufferedOutputStream(connection.
      getOutputStream());

  /** Instantiate an OutputStreamWriter object with the optional character
   * encoding.
   */
  OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");

  String process = "Calling the Socket Server on "+ host + " port " + port;

  /** Write across the socket connection and flush the buffer */
  osw.write(process);
  osw.flush();

<强>客户端:

 /** Instantiate a BufferedInputStream object for reading
      /** Instantiate a BufferedInputStream object for reading
       * incoming socket streams.
       */

      BufferedInputStream bis = new BufferedInputStream(connection.
          getInputStream());
      /**Instantiate an InputStreamReader with the optional
       * character encoding.
       */

      InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");

      /**Read the socket's InputStream and append to a StringBuffer */
      int c;
      while ( (c = isr.read()) != 13)
        instr.append( (char) c);

      /** Close the socket connection. */
      connection.close();
      System.out.println(instr);
     }
    catch (IOException f) {
      System.out.println("IOException: " + f);
    }
    catch (Exception g) {
      System.out.println("Exception: " + g);
    }

希望这会对你有帮助..

答案 1 :(得分:2)

嗨@yuriy您的代码没有任何问题,实际上您没有写完整行到输出流所以它给出错误使用它对我有用

 serverSocket = new ServerSocket(8888);
    socket = serverSocket.accept();
    PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
   output.println("Output string");
    socket.close();

将output.write替换为server

中的output.println

答案 2 :(得分:0)

模拟器监听他自己的“本地”网络端口。 您应该将端口从本地PC调用到模拟器端口。

阅读android adb port forwarding。