'连接重置'在android中通过socket接收数据

时间:2017-03-02 04:40:58

标签: java android sockets tcp

我必须通过WiFi在两个Android设备内发送和接收数据。 当我连接android服务器代码时,代码工作正常。

问题是当我从服务器向客户端发送确认时,它在客户端提供异常。 我必须将数据从客户端发送到服务器,然后它应该将确认返回给客户端。

   W: java.net.SocketException: recvfrom failed: ECONNRESET (Connection reset by peer)
W:     at libcore.io.IoBridge.maybeThrowAfterRecvfrom(IoBridge.java:592)
W:     at libcore.io.IoBridge.recvfrom(IoBridge.java:556)
W:     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:485)
W:     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:37)
W:     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:237)
W:     at java.io.InputStream.read(InputStream.java:162)
W:     at in.co.prosimerp.serverdemo.CleintActivity$MyClientTask.doInBackground(CleintActivity.java:103)
W:     at in.co.prosimerp.serverdemo.CleintActivity$MyClientTask.doInBackground(CleintActivity.java:67)
W:     at android.os.AsyncTask$2.call(AsyncTask.java:292)
W:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
W:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
W:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
W:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
W:     at java.lang.Thread.run(Thread.java:818)
W: Caused by: android.system.ErrnoException: recvfrom failed: ECONNRESET (Connection reset by peer)
W:     at libcore.io.Posix.recvfromBytes(Native Method)
W:     at libcore.io.Posix.recvfrom(Posix.java:185)
W:     at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:250)
W:     at libcore.io.IoBridge.recvfrom(IoBridge.java:553)

客户代码:

    socket = new Socket(dstAddress, dstPort);
                             OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os);
                BufferedWriter bw = new BufferedWriter(osw);
               String number = "2";
               String sendMessage = number + "\n";
                bw.write(sendMessage);
                bw.flush();
                System.out.println("Message sent to the server : "+sendMessage);
                ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream(1024);
                byte[] buffer = new byte[1024];
                int bytesRead;
               InputStream inputStream = socket.getInputStream();
//Exception at this point
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                    response += byteArrayOutputStream.toString("UTF-8");
                }

Sever Code:

 serverSocket = new ServerSocket(SocketServerPORT);
            while (true) {
                Socket socket = serverSocket.accept();
                count++;
                message += "A#" + count + " from " + socket.getInetAddress()
                        + ":" + socket.getPort() + "\n";                 

                OutputStream outputStream;
                String msgReply = "Hello from Android, you are #" + count;

                try {
                    outputStream = socket.getOutputStream();
                    PrintStream printStream = new PrintStream(outputStream);
                    printStream.print(msgReply);
                    printStream.close();

                    message += "replayed: " + msgReply + "\n";

                    MainActivity.this.runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            msg.setText(message);
                        }
                    });

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    message += "Something wrong! " + e.toString() + "\n";
                }}

3 个答案:

答案 0 :(得分:0)

您的客户端正在发送一条从未被服务器读取的消息。当服务器关闭具有未读挂起数据的套接字时,它会导致连接重置而不是正常关闭。

答案 1 :(得分:0)

检查此代码。此代码对我有用。 nis和nos是输入和输出流。

private class SocketserverThread extends Thread {
    @Override
    public void run() {
        super.run();

        try {

            while (true) {
                serverSocket = new ServerSocket();
                serverSocket.setReuseAddress(true);
                serverSocket.bind(new InetSocketAddress(socketServerPORT));
                socket = serverSocket.accept();
                nis = socket.getInputStream();
                nos = socket.getOutputStream();
                byte[] buffer = new byte[1024];
                int bytes;
                bytes = nis.read(buffer);
                if (bytes != -1) {
                    readMessage = new String(buffer, 0, bytes);
                    mainActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
          if (readMessage.length() != 0 || readMessage != "null") {

                                Toast.makeText(getApplicationContext(),readMessage, Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
                }
                nis.close();
                socket.close();
                serverSocket.close();
            }
            // Keep looping to listen for received messages
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }


    }
}

答案 2 :(得分:0)

我有答案

使用available()是唯一的方法,无需借助异步方法。

 while(nis.available()>0){
                        int i=nis.read(buffer, 0, 1024);
                        if(i<0)break;
                        System.out.print("bytes"+new String(buffer, 0, i));
                    }