簡體   English   中英

如何在我的Android應用程序中創建全局客戶端套接字?

[英]How to create a Global Client Socket in my Android Application?

您好親愛的程序員,

我正在嘗試使用android制作井字游戲,我的android應用程序包含多個活動,這些活動之一可以允許客戶端向服務器發送消息,詢問X用戶是否要挑戰,如果用戶接受挑戰,服務器向我發送消息,我們都前進到另一項活動。

我的服務器在我的PC上以常規Java代碼運行,這是我的服務器代碼:

public class Server {

    ServerSocket serverSocket;
    ArrayList<ServerThread> allClients = new ArrayList<ServerThread>();

    public static void main(String[] args) {
        new Server();

    }

    public Server() {
        // ServerSocket is only opened once !!!

        try {
            serverSocket = new ServerSocket(6000);

            System.out.println("Waiting on port 6000...");
            boolean connected = true;

            // this method will block until a client will call me
            while (connected) {
                Socket singleClient = serverSocket.accept();
                // add to the list
                ServerThread myThread = new ServerThread(singleClient);
                allClients.add(myThread);
                myThread.start();
            }

            // here we also close the main server socket
            serverSocket.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    class ServerThread extends Thread {
        Socket threadSocket;
        String userName;
        boolean isClientConnected;
        InputStream input;
        ObjectInputStream ois;
        OutputStream output;
        ObjectOutputStream oos; // ObjectOutputStream

        public ServerThread(Socket s) {
            threadSocket = s;
        }

        public void sendText(String text) {
            try {
                oos.writeObject(text);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public void run() {

            try {
                input = threadSocket.getInputStream();
                ois = new ObjectInputStream(input);
                output = threadSocket.getOutputStream();
                oos = new ObjectOutputStream(output);

                userName = (String) ois.readObject();
                isClientConnected = true;
                System.out.println("User " + userName + " has connected");

                while (isClientConnected) {
                    String singleText = (String) ois.readObject();
                    System.out.println(singleText);

                    for (ServerThread t : allClients)
                        t.sendText(singleText);
                    // oos.writeObject(singleText);
                }
                // close all resources (streams and sockets)
                ois.close();
                oos.close();
                threadSocket.close();

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}    

我僅在兩個活動中使用客戶端之間的通信,兩個活動都包含相同的connectUser()代碼:

public class MenuActivity extends Activity {

    public static final String HOST = "10.0.2.2";
    public static final int PORT = 6000;

    static ConnectThread clientThread;
    boolean isConnected;

    static boolean isOnline = false;


    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        runOnUiThread(new Runnable() {
            public void run() {
                connectUser();

            }
        });
    }

    @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;
    }
    public void connectUser() {
        clientThread = new ConnectThread();
        clientThread.start();


    }

    class ConnectThread extends Thread {
        InputStream input;
        OutputStream output;
        ObjectOutputStream oos;
        Socket s;

        public void sendText(String text) {
            try {
                oos.writeObject(text);
                System.out.println(text);

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        public void run() {
            try {
                s = new Socket(HOST, PORT);
                output = s.getOutputStream();
                oos = new ObjectOutputStream(output);
                oos.writeObject(un);

                isOnline = true;
                isConnected = true;

                new ListenThread(s).start();

            } catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    class ListenThread extends Thread {

        Socket s;
        InputStream input;
        ObjectInputStream ois;

        public ListenThread(Socket s) {
            this.s = s;
            try {
                input = s.getInputStream();
                ois = new ObjectInputStream(input);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        public void run() {
            while (isConnected) {
                try {
                    final String inputMessage = (String) ois.readObject();
                //do something with the message                 }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    }

}

我使用此代碼將此代碼發送消息到服務器:

                clientThread.sendText(user + " " + opponent + " play");

問題是,當我在第一個活動中創建連接,然后移至第二個活動時,我創建了另一個連接,這意味着到目前為止,我有兩個連接,與其他客戶端相同,然后服務器似乎返回了超時錯誤。

我的問題是如何創建一次創建的全局客戶端變量,該變量可以在每個活動中使用。 我看到了許多建議,例如套接字服務或asyntask,但是我需要更多的指導和幫助

提前致謝。

將Application的子類添加到您的項目中,並更新應用程序標簽,並將該類添加為android:name:

<application
    android:name="com.your.app.MyApplication"
...

然后在MyApplication類中創建對您的Socket連接的靜態引用:

private static Socket connection;

然后添加一個靜態方法來訪問該對象:

public static Socket getConnection() {
    if( connection == null) {
        // initialize connection object here
    }
    return connection;
}

現在您有了一個全局對象!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM