Android: Socket is closed

2020-05-08 06:54发布

问题:

PCClient :

public class PCServer
{

/**
 * @param args
 */
static Socket socket = null;
private static String ip = "192.168.42.129";
private static int port = 18181;

public static void main(String[] args)
{
    // TODO Auto-generated method stub
    try
    {
        socket = new Socket(ip, port);
    } catch (UnknownHostException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1)
    {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try
    {
        SendMsg(ip, port, "BZT");
        GetMessage getMessage = new GetMessage();
        getMessage.start();
    } catch (UnknownHostException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static void SendMsg(String ip, int port, String msg) throws UnknownHostException, IOException
{
    try
    {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        writer.write(msg);
        writer.flush();
        writer.close();
        //socket.close();
    } catch (UnknownHostException e)
    {
        e.printStackTrace();
    } catch (IOException e)
    {
        e.printStackTrace();
    }
}

static class GetMessage extends Thread
{
    @Override
    public void run()
    {
        // TODO Auto-generated method stub
        super.run();
        try
        {
            while (true)
            {
                System.out.println("--------------------------------------------------------");
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String str = in.readLine();
                System.out.println(str);
                //client.close();
            }
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
  }
}

AndroidServer : Service

public class SocketService extends Service
{
public static final int SERVERPORT = 18181;
ServerSocket serverSocket;
@Override
public IBinder onBind(Intent arg0)
{
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    // TODO Auto-generated method stub
    try
    {
        serverSocket = new ServerSocket(SERVERPORT);
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    GetSocketMessage getSocketMessage = new GetSocketMessage();
    getSocketMessage.start();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy()
{
    // TODO Auto-generated method stub
    super.onDestroy();
    try
    {
        this.serverSocket.close();
    } 
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

class GetSocketMessage extends Thread
{
    @Override
    public void run()
    {
        // TODO Auto-generated method stub
        super.run();
        try
        {
            Log.i("s", "S: Connecting...");
            while (true)
            {
                Socket client = serverSocket.accept();
                Log.i("s", "S: Receiving...");
                try
                {
                    BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
                    String str = in.readLine();
                    Log.i("s", "S: Received: '" + str + "'");

                    if ("BZT".equals(str))
                    {
                        Intent intent =  new Intent("com.StarHope.ZWGKXT.connected");
                        sendBroadcast(intent);
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                        writer.write("OK");
                        writer.flush();
                        writer.close();
                    }
                    if ( Lbjy_usbActivity.content !=null )
                    {
                        Log.i("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "oooooooooooooooooooooooooooooo");
                        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
                        writer.write("");
                        writer.flush();
                        writer.close();
                    }
                } 
                catch (Exception e)
                {
                    Log.i("s", "S: Error");
                    e.printStackTrace();
                } 
                finally
                {
                    Log.i("s", "S: Done");
                }
            }
        } 
        catch (Exception e)
        {
            Log.i("s", "S: Error");
            e.printStackTrace();
        }
    }
  }
}

The android phone server can received the message sent from PCClient "BZT", But when the phone send "OK" to PC , there is always an

Exception:java.net.SocketException: Socket is closed.

How can I fix this?

回答1:

Closing any stream obtained using getOutputStream() or getInputStream() closes the socket.

Do you receive something before 'BZT' ? If so, the socket will be closed after you sent the empty answer.

You should use only one output stream, and flush() each message without closing.