繁体   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