将Android套接字客户端连接到C套接字服务器

时间:2017-02-23 20:23:06

标签: java android c sockets

我想通过Android应用程序将一些数据发送到c服务器。

我已经按照this教程获得了基本框架。

我替换了以下代码

        socket = new Socket(dstAddress, dstPort);

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
                1024);
        byte[] buffer = new byte[1024];

        int bytesRead;
        InputStream inputStream = socket.getInputStream();

        /*
         * notice: inputStream.read() will block if no data return
         */
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, bytesRead);
            response += byteArrayOutputStream.toString("UTF-8");
        }

用我自己的

     System.out.println("Connecting to " + serverName + " on port " + port);
     Socket client = new Socket(serverName, port);
     System.out.println("Just connected to " + client.getRemoteSocketAddress());

     PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));

     outToServer.println("Hello from " + client.getLocalSocketAddress());
     outToServer.flush();

     BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
     System.out.println("Server Says : " + in.readLine());

我测试了我的java代码,它正确地发送和接收数据,但是当我尝试在android中做同样的事情时,我会陷入困境

Socket client = new Socket(serverName, port);

我可以从Android Monitor中看到它打印

I/System.out: Connecting to 100.82.232.126 on port 5001

然后它就会挂起。

0 个答案:

没有答案