简体   繁体   English

Android tcp客户端连接然后从Java服务器断开连接

[英]Android tcp client connects then disconnect from java server

I am doing java server on my pc and having my android device connect to it. 我正在PC上做Java服务器,并让我的Android设备连接到它。 I can connect it but it disconnects as soon as it connects. 我可以连接它,但是一旦连接它就会断开连接。 I am sure there is something I need to do on the android side but I am little lost on it. 我敢肯定,我需要在android方面做一些事情,但是我对此并没有什么迷失。 I have the internet permission so that is fine. 我有互联网许可,所以很好。

Also ignore the commented code I was sending image from my android to pc. 也请忽略我将图像从Android发送到PC的注释代码。 Also ignore the savebitmap and take screenshot I don't think its affecting the connection if its not being called. 还要忽略savebitmap并截取屏幕快照,如果不调用它,它不会影响连接。

Java Server: Java服务器:

import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*; //access JFrame
import javax.swing.text.html.HTMLDocument.Iterator;

import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;

public class tcpmain {

    BufferedReader in;

    static final int PORT = 9000;
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        //lines to make the gui frame
        JFrame mainframe = new JFrame();
        mainframe.setTitle("TCP Listener");
        mainframe.setSize(600,800);
        mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainframe.setVisible(true);


        ServerSocket serverSocket = null;
        Socket socket = null;
        try{
            serverSocket = new ServerSocket(PORT);



            //Receive code
            /*int filesize=450660;
            int bytesRead;
            int current=0;

            //receive file
            byte [] mybytearray = new byte [filesize];
            InputStream is = srsvsock.getInputStream();
            FileOutputStream fos = new FileOutputStream("C:\\Users\\Andy\\Desktop\\testimage.jpg");
            BufferedOutputStream bos = new BufferedOutputStream(fos);
            bytesRead = is.read(mybytearray,0,mybytearray.length);
            current = bytesRead;*/

            /*do{
                bytesRead = 
                        is.read(mybytearray, current, (mybytearray.length-current));
                if(bytesRead >= 0) current += bytesRead;
            } while(bytesRead > -1);

            bos.write(mybytearray, 0, current);
            bos.flush();*/


           }
            catch(Exception e){
                e.printStackTrace();
            }
        while (true) {
            try {
                socket = serverSocket.accept();
                JOptionPane.showMessageDialog(null, "Client connected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException e) {
                System.out.println("I/O error: " + e);
            }
            // new threa for a client
            new EchoThread(socket).start();
            if ( socket != null && !socket.isClosed() ){
                try {
                    socket.close();
                    JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }


        }


    }

client handler for java server Java服务器的客户端处理程序

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;


public class EchoThread extends Thread {
    protected Socket socket;



    public EchoThread(Socket clientSocket){
        this.socket = clientSocket;
    }
    public void run(){
        InputStream inp = null;
        BufferedReader brinp = null;
        DataOutputStream out = null;
        try{
            inp = socket.getInputStream();
            brinp = new BufferedReader(new InputStreamReader(inp));
            out = new DataOutputStream(socket.getOutputStream());
        }catch(Exception e){
            return;

        }
        String line;
        while(true){
            try{
                line = brinp.readLine();
                if ((line == null) || line.equalsIgnoreCase("QUIT")){
                    socket.close();
                    return;

                }else{
                    out.writeBytes(line+ "\n\r");
                    out.flush();
                }
            }catch(Exception e){
                e.printStackTrace();
                return;
            }
        }

    }



}

Here is android client: 这是android客户端:

package com.example.tcpsocket;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private Socket socket;

    private static final int SERVERPORT = 9000;

    private static final String SERVER_IP = "192.168.1.113";

    Bitmap bitmap;
    File imagePath;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnconnect = (Button)findViewById(R.id.button1);
        btnconnect.setOnClickListener(connect);

    }

    private OnClickListener connect = new OnClickListener(){

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            //Bitmap bitmap = takeScreenshot();
              // saveBitmap(bitmap);
            new Thread(new clienthread()).start();

        }

    };

    public Bitmap takeScreenshot() {
           View rootView = findViewById(android.R.id.content).getRootView();
           rootView.setDrawingCacheEnabled(true);
           return rootView.getDrawingCache();
        }

    public void saveBitmap(Bitmap bitmap){
         File imagePath = new File("sdcard/screenshot.jpg");
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(imagePath);
                bitmap.compress(CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
                new Thread(new clienthread()).start();
            } catch (FileNotFoundException e) {
                Log.e("GREC", e.getMessage(), e);
            } catch (IOException e) {
                Log.e("GREC", e.getMessage(), e);
            }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    class clienthread implements Runnable {


        @Override
        public void run() {
            // TODO Auto-generated method stub
            try{
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
                /*File imagePath = new File("sdcard/screenshot.jpg");




                byte[] mybytearray = new byte[450560];
                FileInputStream fis = new FileInputStream(imagePath);
                BufferedInputStream bis = new BufferedInputStream(fis);
                bis.read(mybytearray,0,mybytearray.length);
                OutputStream os = socket.getOutputStream();
                os.write(mybytearray,0,mybytearray.length);
                os.close();*/
            }
            catch(Exception e){


            }
        }


    }





}

Here: 这里:

        new EchoThread(socket).start();
        if ( socket != null && !socket.isClosed() ){
            try {
                socket.close();//Don't do this here!!!!!!
                JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

You shouldn't close your socket after you started your Thread. 启动线程后,您不应该关闭套接字。 The closing of the socket should be the job of the EchoThread after you finished communicating with it. 完成与EchoThread的通信之后,应该关闭套接字。 You can insert this line at the end of run() method socket.close(); 您可以在run()方法socket.close();的末尾插入此行socket.close(); so it closes itself when you're done. 因此完成后它会自行关闭。

Looks like it is most likely due to this line: 看起来很可能是由于以下原因:

       if ( socket != null && !socket.isClosed() ){

If your socket was previously opened and you passed if off to the thread to handle, the socket would still be open and socket.isClosed() will return false and you'll immediately close the socket and clean it up in your main thread. 如果您以前打开过套接字,并且传递给要处理的线程,则该套接字仍将处于打开状态,并且socket.isClosed()将返回false,您将立即关闭套接字并在主线程中对其进行清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM