简体   繁体   English

为什么我的服务器和客户端在服务器活动开始时断开连接?

[英]Why do my server and client disconnect on server activity start?

I posted this in a different location previously and was promptly downvoted into oblivion.我之前在不同的位置发布了这个,但很快就被否决了。 I have since deleted and tried to refine it at least a little, as well as put it in a more appropriate place.从那以后,我已经删除并尝试至少对其进行一些改进,并将其放在更合适的位置。 Please tell me how to make the post more clear if I am doing something wrong, I am still fairly new to posting on this site.如果我做错了什么,请告诉我如何使帖子更清晰,我对在这个网站上发帖还是很陌生。

The idea here is to make a socket connection over the local network, send some data, and close the connection immediately.这里的想法是在本地网络上建立一个socket连接,发送一些数据,然后立即关闭连接。 The only thing that should remain running is the serversocket .唯一应该保持运行的是serversocket So far, everything works as expected except one thing:到目前为止,一切都按预期工作,除了一件事:

When the activity that starts the serversocket gets closed with the back button, and then reopened, the data being sent from the client no longer makes it to the serversocket .当启动serversocket的活动使用后退按钮关闭,然后重新打开时,从客户端发送的数据不再发送到serversocket

DMActivity: DM活动:

public class DMActivity extends AppCompatActivity {

    String ipAddress;
    boolean dmListenRunning = false;
    DMListen dmListen = new DMListen();
    Thread dmListenThread;


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

        if (!(dmListenRunning)) {
            dmListenThread = new Thread(dmListen);
            dmListenRunning = true;

            dmListenThread.start();
        }
    }

    @Override
    public void onBackPressed()
    {
        try {
            dmListen.KillThread(true);
            dmListenThread.interrupt();
        }

        catch (Exception e)
        {
            Log.i("LOG", e.toString());
        }

        finish();
    }
}

DMListen: DM听:

public class DMListen implements Runnable {

    ServerSocket serverSocket;
    boolean started = false;
    boolean closeSockets = false;
    boolean killed = false;

    public void run() {
        ReceivePlayerData();
    }

    public void ReceivePlayerData() {
        try {
            while (!(Thread.interrupted())) {
                if (!(started)) {
                    int port = 8080;
                    serverSocket = new ServerSocket(port);
                    started = true;
                }

                Socket clientSocket = serverSocket.accept();
                DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());
                String name;
                int init;

                name = dataIn.readUTF();
                init = dataIn.readInt();
                dataIn.close();
                clientSocket.close();
            }
        }

catch (Exception e) {
              Log.i("LOG", e.toString();
        }

        if(killed)
        {
            try {
                serverSocket.close();

                if (Thread.currentThread().isInterrupted())
                {
                    try {
                        Thread.currentThread().join();
                    }

                    catch (Exception e)
                    {
                        Log.i("LOG", e.toString());
                    }
                }
            }

            catch(IOException e)
            {
                Log.i("LOG", e.toString());
            }
        }
    }

    public void KillThread(boolean k)
    {
        boolean killed = k;
    }
}

PlayerActivity:玩家活动:

public class PlayerActivity extends AppCompatActivity {

    EditText hostIPBox;
    Button submit;
    String hostIPString;
    InetAddress hostIP;
    boolean denied = false;
    boolean started = false;
    PlayerConnect playerConnect;

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

        hostIPBox = (EditText) findViewById(R.id.ipaddress);
        hostIPBox.setRawInputType(Configuration.KEYBOARD_12KEY);
        hostIPBox.setSingleLine();
        submit = (Button) findViewById(R.id.submit);

        submit.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                hostIPString = hostIPBox.getText().toString();

                try {
                        if (!(hostIPString.equals(""))) {
                            hostIP = InetAddress.getByName(hostIPString);
                            if(!(started)) {
                                playerConnect = new PlayerConnect();
                                playerConnect.SetHostIP(hostIP);
                                denied = playerConnect.GetDenied();
                                started = true;
                            }

                            else {
                                playerConnect.SetHostIP(hostIP);
                                denied = playerConnect.GetDenied();
                            }


                            if (denied)
                            {
                                started = false;
                            }

                            else
                            {
                                new Thread(playerConnect).start();
                            }
                        }
                    }

                    catch (Exception e) {
                        Log.e("LOG", e.toString());
                    }
                }
        });
    }
}

PlayerConnect:玩家连接:

public class PlayerConnect implements Runnable {

    InetAddress hostIP;
    boolean closeSockets = false;
    boolean denied = false;

    public void run() {
            SendPlayerData(hostIP, playerName, playerInitiative);
    }

    private void SendPlayerData(InetAddress IP, String name, int init) {
        try {
            int port = 8080;
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(IP, port), 3000);
            DataOutputStream output = new DataOutputStream(socket.getOutputStream());

            if (socket.isConnected())
            {
                output.writeUTF(name);
                output.writeInt(init);
                output.close();
                socket.close();
            }

            if (closeSockets) {
                output.close();
                socket.close();
                closeSockets = false;
            }
        }

        catch (Exception e) {
            denied = true;
    Log.i("LOG", e.printStackTrace());
        }
    }

    public void SetHostIP(InetAddress host)
    {
        hostIP = host;
    }

    public boolean GetDenied()
    {
        return denied;
    }
}

You should use Service to handle socket connection.您应该使用 Service 来处理套接字连接。 You won't have problems with Activity lifecycle. Activity 生命周期不会有问题。

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

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