Android的TCP连接(多客户端) [英] Android TCP Connection (Multiple Client)

查看:376
本文介绍了Android的TCP连接(多客户端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个(Android的TCP连接增强型)教程创建简单的JAVA TCPSERVER ANA的Andr​​oid的TcpClient。它的工作原理完美的,但与此$ C $词可以在同一时间只有一台设备连接到服务器。我有什么改变与多个设备连接?​​

JAVA服务器:常量

公共类常量{     公共静态最后弦乐CLOSED_CONNECTION =kazy_closed_connection;     公共静态最后弦乐LOGIN_NAME =kazy_login_name; }

JAVA服务器:MainScreen

公共类MainScreen扩展的JFrame {     / **      *      * /     私有静态最后长的serialVersionUID = 8399514248326995812L;     私人的JTextArea messagesArea;     私人JButton的sendButton;     私人JTextField的消息;     私人JButton的startserver的;     私人JButton的stopServer;     私人TCPSERVER mServer上;     公共MainScreen(){         超级(MainScreen);         JPanel的panelFields =新的JPanel();         panelFields.setLayout(新的BoxLayout(panelFields,BoxLayout.X_AXIS));         JPanel的panelFields2 =新的JPanel();         panelFields2.setLayout(新的BoxLayout(panelFields2,BoxLayout.X_AXIS));         //这里我们将有短信屏幕         messagesArea =新的JTextArea();         messagesArea.setColumns(30);         messagesArea.setRows(10);         messagesArea.setEditable(假);         sendButton =新的JButton(发送);         sendButton.addActionListener(新的ActionListener(){             @覆盖             公共无效的actionPerformed(ActionEvent的E){                 //从文本视图消息                 串的MessageText = message.getText();                 //添加消息到消息区                 messagesArea.append(\ N+的MessageText);                 如果(mServer上!= NULL){                     //将消息发送给客户端                     mServer.sendMessage(的MessageText);                 }                 //明文                 message.setText();             }         });         startserver的=新的JButton(开始);         startServer.addActionListener(新的ActionListener(){             @覆盖             公共无效的actionPerformed(ActionEvent的E){                 //创建对象OnMessageReceived问的TCPSERVER                 //构造                 mServer上=新TCPSERVER(新TcpServer.OnMessageReceived(){                     @覆盖                     //此方法宣布从TCPSERVER接口                     //类是这里实现                     //这个方法实际上是一个回调方法,因为它                     //将运行每当它会从所谓的时间                     // TCPSERVER类(在一段时间)                     公共无效的messageReceived(字符串消息){                         messagesArea.append(\ N+消息);                     }                 });                 mServer.start();                 //禁用启动按钮,并启用站有一个                 startServer.setEnabled(假);                 stopServer.setEnabled(真正的);             }         });         stopServer =新的JButton(停止);         stopServer.addActionListener(新的ActionListener(){             @覆盖             公共无效的actionPerformed(ActionEvent的E){                 如果(mServer上!= NULL){                     mServer.close();                 }                 //禁用停止按钮,使Start跳过                 startServer.setEnabled(真正的);                 stopServer.setEnabled(假);             }         });         //用户在其中输入的文本框(的EditText中调用         //安卓)         消息=新的JTextField();         message.setSize(200,20);         //添加按钮和文本字段到面板         panelFields.add(messagesArea);         panelFields.add(startserver的);         panelFields.add(stopServer);         panelFields2.add(消息);         panelFields2.add(sendButton);         getContentPane()加(panelFields)。         getContentPane()加(panelFields2)。         getContentPane()。setLayout的(                 新的BoxLayout(getContentPane(),BoxLayout.Y_AXIS));         的setSize(300,170);         的setVisible(真);     } }

JAVA服务器:TCPSERVER

公共类TCPSERVER继承Thread {     公共静态最终诠释SERVERPORT = 4444;     //而这是真实的服务器将运行     私人布尔运行= FALSE;     //用于发送邮件     私人PrintWriter的bufferSender;     //回调用于通知收到新邮件     私人OnMessageReceived消息监听;     私人的ServerSocket ServerSocket的;     私人客户端的Socket;     / **      *类的构造函数      *      * @参数消息监听      *监听消息      * /     公共TCPSERVER(OnMessageReceived消息监听){         this.messageListener =消息监听;     }     公共静态无效的主要(字串[] args){         //打开那里的信息将被接收和发送窗口         MainScreen帧=新MainScreen();         frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);         frame.pack();         frame.setVisible(真正的);     }     / **      *关闭服务器      * /     公共无效的close(){         运行= FALSE;         如果(bufferSender!= NULL){             bufferSender.flush();             bufferSender.close();             bufferSender = NULL;         }         尝试 {             client.close();             serverSocket.close();         }赶上(例外五){             e.printStackTrace();         }         的System.out.println(S:完成。);         ServerSocket的= NULL;         客户端= NULL;     }     / **      *方法从服务器发送的邮件客户端      *      * @参数信息      *由服务器发送的消息      * /     公共无效的sendMessage(字符串消息){         如果(bufferSender =空&安培;!&安培;!bufferSender.checkError()){             bufferSender.println(消息);             bufferSender.flush();         }     }     公共布尔hasCommand(字符串消息){         如果(消息!= NULL){             如果(message.contains(Constants.CLOSED_CONNECTION)){                 messageListener.messageReceived(message.replaceAll(                         Constants.CLOSED_CONNECTION,)                         +断开);                 //关闭服务器连接,如果我们有这样的命令,并                 //重新构建一个新的                 关闭();                 RUNSERVER();                 返回true;             }否则,如果(message.contains(Constants.LOGIN_NAME)){                 messageListener.messageReceived(message.replaceAll(                         Constants.LOGIN_NAME,)+连接);                 返回true;             }         }         返回false;     }     / **      *构建一个新的服务器连接      * /     私人无效RUNSERVER(){         运行=真;         尝试 {             的System.out.println(S:连接......);             //创建一个服务器套接字。服务器套接字等待请求             //进来在网络上。             ServerSocket的=新的ServerSocket(SERVERPORT);             //创建客户端套接字...方法接受()侦听             //才能进行连接到此插座,接受它。             客户端的ServerSocket.accept =();             的System.out.println(S:接收...);             尝试 {                 //将消息发送到客户端                 bufferSender =的新PrintWriter(新的BufferedWriter(                         新OutputStreamWriter(client.getOutputStream())),TRUE);                 //读取客户端接收到的消息                 的BufferedReader在=新的BufferedReader(新的InputStreamReader(                         client.getInputStream()));                 //这个在我们等待从客户端接收消息(它是                 //无限循环)                 //这个而它就像一个消息侦听器                 而(运行){                     字符串消息= NULL;                     尝试 {                         消息= in.readLine();                     }赶上(IOException异常E){                         的System.out.println(读取错误信息:                                 + e.getMessage());                     }                     如果(hasCommand(消息)){                         继续;                     }                     如果(消息= NULL和放大器;!&安培;!消息监听= NULL){                         //调用来自服务器主板的messageReceived方法                         // 类                         messageListener.messageReceived(消息);                     }                 }             }赶上(例外五){                 的System.out.println(S:错误);                 e.printStackTrace();             }         }赶上(例外五){             的System.out.println(S:错误);             e.printStackTrace();         }     }     @覆盖     公共无效的run(){         super.run();         RUNSERVER();     }     //声明的接口。该方法的messageReceived(字符串消息)会     //必须在服务器主板中实现     //班的startserver的按钮点击     公共接口OnMessageReceived {         公共无效的messageReceived(字符串消息);     } }

Android客户端:的TcpClient

公共类的TcpClient {     公共静态最后弦乐SERVER_IP =192.168.0.102; //你的电脑的IP                                                             // 地址     公共静态最终诠释SERVER_PORT = 4444;     //消息以发送到服务器     私人字符串mServerMessage;     //将收到邮件通知     私人OnMessageReceived mMessageListener = NULL;     //而这是真的,服务器将继续运行     私人布尔mRun = FALSE;     //用于发送邮件     私人PrintWriter的mBufferOut;     //用于从服务器读取消息     私人的BufferedReader mBufferIn;     私人字符串的UID;     / **      *类的构造函数。 OnMessagedReceived监听消息      *从服务器接收到      * /     公众的TcpClient(OnMessageReceived监听器){         mMessageListener =侦听器;     }     / **      *发送由客户输入到服务器的消息      *      * @参数信息      *通过客户端输入的文本      * /     公共无效的sendMessage(字符串消息){         如果(mBufferOut =空&安培;!&安培;!mBufferOut.checkError()){             mBufferOut.println(消息);             mBufferOut.flush();         }     }     / **      *关闭连接并释放成员      * /     公共无效stopClient(){         //发送,我们正在关闭连接mesage         TelephonyManager tManager =(TelephonyManager)MyApplication.getInstance()getSystemService(Context.TELEPHONY_SERVICE)。         UID = tManager.getDeviceId();         的sendMessage(Constants.CLOSED_CONNECTION +号:+ UID);         mRun = FALSE;         如果(mBufferOut!= NULL){             mBufferOut.flush();             mBufferOut.close();         }         mMessageListener = NULL;         mBufferIn = NULL;         mBufferOut = NULL;         mServerMessage = NULL;     }     公共无效的run(){         mRun = TRUE;         尝试 {             //在这里你必须把你的计算机的IP地址。             InetAddress类serverAddr = InetAddress.getByName(SERVER_IP);             MyLog.e(TCP客户端,C:连接...);             //创建一个插座,使与服务器的连接             Socket套接字=新的Socket(serverAddr,SERVER_PORT);             尝试 {                 //将消息发送至服务器                 mBufferOut =的新PrintWriter(新的BufferedWriter(                         新OutputStreamWriter(socket.getOutputStream())),TRUE);                 //接收服务器发送的讯息                 mBufferIn =新的BufferedReader(新的InputStreamReader(                         socket.getInputStream()));                 //发送的登录名                 TelephonyManager tManager =(TelephonyManager)MyApplication.getInstance()getSystemService(Context.TELEPHONY_SERVICE)。                 UID = tManager.getDeviceId();                 的sendMessage(Constants.LOGIN_NAME +号:+ UID);                 //在此同时,在客户端监听被发送的消息                 // 服务器                 而(mRun){                     mServerMessage = mBufferIn.readLine();                     如果(mServerMessage = NULL和放大器;!&安培;!mMessageListener = NULL){                         //调用该方法的messageReceived从MyActivity类                         mMessageListener.messageReceived(mServerMessage);                     }                 }                 MyLog.e(响应从服务器,S:收到的消息:'                         + mServerMessage +');             }赶上(例外五){                 MyLog.e(TCP,S:错误,E);             } 最后 {                 //插座必须关闭。这是不可能的重新连接到                 //此套接字                 //在关闭之后,这意味着新的套接字实例具有至                 //创建。                 socket.close();             }         }赶上(例外五){             MyLog.e(TCP,C:错误,E);         }     }     //声明的接口。该方法的messageReceived(字符串消息)会     //必须在MyActivity实施     //班的asynckTask doInBackground     公共接口OnMessageReceived {         公共无效的messageReceived(字符串消息);     } }

Android客户端:常量

公共类常量{     公共静态最后弦乐CLOSED_CONNECTION =kazy_closed_connection;     公共静态最后弦乐LOGIN_NAME =kazy_login_name; }

Android客户端:我的活动

@覆盖 保护无效的onPause(){     super.onPause();     如果(连接!= NULL){         connect.cancel(真正的);     }     如果(mTcpClient!= NULL){         MyLog.d(TAG,stopClient);         mTcpClient.stopClient();         mTcpClient = NULL;     } } 公共类ConnectTask扩展的AsyncTask<字符串,字符串,的TcpClient> {     @覆盖     受保护的TcpClient doInBackground(字符串...消息){         MyLog.d(TAG,doInBackground);         //我们创建的TcpClient对象,         mTcpClient =新的TcpClient(新TCPClient.OnMessageReceived(){             @覆盖             //这里的messageReceived方法的实施             公共无效的messageReceived(字符串消息){                 //此方法调用onProgressUpdate                 publishProgress(消息);             }         });         mTcpClient.run();         返回null;     }     @覆盖     保护无效onProgressUpdate(字符串...值){         super.onProgressUpdate(值);         MyLog.d(TAG,onProgressUpdate);         查看查看= adapter.getChildView(0,0,假,空,空);         TextView的文字=(TextView的)view.findViewById(R.id.betChildOdd);         child2.get(0)获得(0)。把(旧,text.getText()的toString());         child2.get(0)获得(0)。把(CONVERTED_ODDS,值[0]的ToString());         child2.get(0)获得(0)。把(CHANGE,真);         adapter.notifyDataSetChanged();     } }

解决方案

我没有去通过所有的code但来到我的脑海里的第一件事是:你是基于多线程的服务器上构建应用程序建筑?对于我在你的code看见了,我注意到,你没有委托什么来了socket.accept(后)到另一个线程的执行,这就是为什么你不能同时接听多个客户端。

记住,你需要采取的并发访问同一数据结构可能产生的竞争条件的照顾。

这是你应该遵循你的TCP服务器模式:http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

I use this (Android TCP Connection Enhanced) tutorial to create simple JAVA TCPServer ana Android TCPClient. It works perfect, but with this code i can connect only one device to the server at the same time. What do I have to change to connect with several devices?

JAVA Server: Constants

public class Constants {

    public static final String CLOSED_CONNECTION = "kazy_closed_connection";
    public static final String LOGIN_NAME = "kazy_login_name";

}

JAVA Server: MainScreen

public class MainScreen extends JFrame {

    /**
     * 
     */
    private static final long serialVersionUID = 8399514248326995812L;
    private JTextArea messagesArea;
    private JButton sendButton;
    private JTextField message;
    private JButton startServer;
    private JButton stopServer;
    private TcpServer mServer;

    public MainScreen() {

        super("MainScreen");

        JPanel panelFields = new JPanel();
        panelFields.setLayout(new BoxLayout(panelFields, BoxLayout.X_AXIS));

        JPanel panelFields2 = new JPanel();
        panelFields2.setLayout(new BoxLayout(panelFields2, BoxLayout.X_AXIS));

        // here we will have the text messages screen
        messagesArea = new JTextArea();
        messagesArea.setColumns(30);
        messagesArea.setRows(10);
        messagesArea.setEditable(false);

        sendButton = new JButton("Send");
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // get the message from the text view
                String messageText = message.getText();
                // add message to the message area
                messagesArea.append("\n" + messageText);
                if (mServer != null) {
                    // send the message to the client
                    mServer.sendMessage(messageText);
                }
                // clear text
                message.setText("");
            }
        });

        startServer = new JButton("Start");
        startServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                // creates the object OnMessageReceived asked by the TCPServer
                // constructor
                mServer = new TcpServer(new TcpServer.OnMessageReceived() {
                    @Override
                    // this method declared in the interface from TCPServer
                    // class is implemented here
                    // this method is actually a callback method, because it
                    // will run every time when it will be called from
                    // TCPServer class (at while)
                    public void messageReceived(String message) {
                        messagesArea.append("\n " + message);
                    }
                });
                mServer.start();

                // disable the start button and enable the stop one
                startServer.setEnabled(false);
                stopServer.setEnabled(true);

            }
        });

        stopServer = new JButton("Stop");
        stopServer.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                if (mServer != null) {
                    mServer.close();
                }

                // disable the stop button and enable the start one
                startServer.setEnabled(true);
                stopServer.setEnabled(false);

            }
        });

        // the box where the user enters the text (EditText is called in
        // Android)
        message = new JTextField();
        message.setSize(200, 20);

        // add the buttons and the text fields to the panel
        panelFields.add(messagesArea);
        panelFields.add(startServer);
        panelFields.add(stopServer);

        panelFields2.add(message);
        panelFields2.add(sendButton);

        getContentPane().add(panelFields);
        getContentPane().add(panelFields2);

        getContentPane().setLayout(
                new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));

        setSize(300, 170);
        setVisible(true);
    }

}

JAVA Server: TcpServer

public class TcpServer extends Thread {

    public static final int SERVERPORT = 4444;
    // while this is true the server will run
    private boolean running = false;
    // used to send messages
    private PrintWriter bufferSender;
    // callback used to notify new messages received
    private OnMessageReceived messageListener;
    private ServerSocket serverSocket;
    private Socket client;

    /**
     * Constructor of the class
     * 
     * @param messageListener
     *            listens for the messages
     */
    public TcpServer(OnMessageReceived messageListener) {
        this.messageListener = messageListener;
    }

    public static void main(String[] args) {

        // opens the window where the messages will be received and sent
        MainScreen frame = new MainScreen();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);

    }

    /**
     * Close the server
     */
    public void close() {

        running = false;

        if (bufferSender != null) {
            bufferSender.flush();
            bufferSender.close();
            bufferSender = null;
        }

        try {
            client.close();
            serverSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("S: Done.");
        serverSocket = null;
        client = null;

    }

    /**
     * Method to send the messages from server to client
     * 
     * @param message
     *            the message sent by the server
     */
    public void sendMessage(String message) {
        if (bufferSender != null && !bufferSender.checkError()) {
            bufferSender.println(message);
            bufferSender.flush();
        }
    }

    public boolean hasCommand(String message) {
        if (message != null) {
            if (message.contains(Constants.CLOSED_CONNECTION)) {
                messageListener.messageReceived(message.replaceAll(
                        Constants.CLOSED_CONNECTION, "")
                        + " disconnected");
                // close the server connection if we have this command and
                // rebuild a new one
                close();
                runServer();
                return true;
            } else if (message.contains(Constants.LOGIN_NAME)) {
                messageListener.messageReceived(message.replaceAll(
                        Constants.LOGIN_NAME, "") + " connected");
                return true;
            }
        }

        return false;
    }

    /**
     * Builds a new server connection
     */
    private void runServer() {
        running = true;

        try {
            System.out.println("S: Connecting...");

            // create a server socket. A server socket waits for requests to
            // come in over the network.
            serverSocket = new ServerSocket(SERVERPORT);

            // create client socket... the method accept() listens for a
            // connection to be made to this socket and accepts it.
            client = serverSocket.accept();

            System.out.println("S: Receiving...");

            try {

                // sends the message to the client
                bufferSender = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(client.getOutputStream())), true);

                // read the message received from client
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        client.getInputStream()));

                // in this while we wait to receive messages from client (it's
                // an infinite loop)
                // this while it's like a listener for messages
                while (running) {

                    String message = null;
                    try {
                        message = in.readLine();
                    } catch (IOException e) {
                        System.out.println("Error reading message: "
                                + e.getMessage());
                    }

                    if (hasCommand(message)) {
                        continue;
                    }

                    if (message != null && messageListener != null) {
                        // call the method messageReceived from ServerBoard
                        // class
                        messageListener.messageReceived(message);
                    }
                }

            } catch (Exception e) {
                System.out.println("S: Error");
                e.printStackTrace();
            }

        } catch (Exception e) {
            System.out.println("S: Error");
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        super.run();

        runServer();

    }

    // Declare the interface. The method messageReceived(String message) will
    // must be implemented in the ServerBoard
    // class at on startServer button click
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }

}

Android Client: TCPClient

public class TCPClient {

    public static final String SERVER_IP = "192.168.0.102"; // your computer IP
                                                            // address
    public static final int SERVER_PORT = 4444;
    // message to send to the server
    private String mServerMessage;
    // sends message received notifications
    private OnMessageReceived mMessageListener = null;
    // while this is true, the server will continue running
    private boolean mRun = false;
    // used to send messages
    private PrintWriter mBufferOut;
    // used to read messages from the server
    private BufferedReader mBufferIn;

    private String uid;

    /**
     * Constructor of the class. OnMessagedReceived listens for the messages
     * received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * 
     * @param message
     *            text entered by client
     */
    public void sendMessage(String message) {
        if (mBufferOut != null && !mBufferOut.checkError()) {
            mBufferOut.println(message);
            mBufferOut.flush();
        }
    }

    /**
     * Close the connection and release the members
     */
    public void stopClient() {

        // send mesage that we are closing the connection
        TelephonyManager tManager = (TelephonyManager) MyApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
        uid = tManager.getDeviceId();
        sendMessage(Constants.CLOSED_CONNECTION + "id: " + uid);

        mRun = false;

        if (mBufferOut != null) {
            mBufferOut.flush();
            mBufferOut.close();
        }

        mMessageListener = null;
        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;
    }

    public void run() {

        mRun = true;

        try {
            // here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            MyLog.e("TCP Client", "C: Connecting...");

            // create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVER_PORT);

            try {

                // sends the message to the server
                mBufferOut = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())), true);

                // receives the message which the server sends back
                mBufferIn = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                // send login name
                TelephonyManager tManager = (TelephonyManager) MyApplication.getInstance().getSystemService(Context.TELEPHONY_SERVICE);
                uid = tManager.getDeviceId();
                sendMessage(Constants.LOGIN_NAME + "id: " + uid);

                // in this while the client listens for the messages sent by the
                // server
                while (mRun) {

                    mServerMessage = mBufferIn.readLine();

                    if (mServerMessage != null && mMessageListener != null) {
                        // call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(mServerMessage);
                    }

                }

                MyLog.e("RESPONSE FROM SERVER", "S: Received Message: '"
                        + mServerMessage + "'");

            } catch (Exception e) {

                MyLog.e("TCP", "S: Error", e);

            } finally {
                // the socket must be closed. It is not possible to reconnect to
                // this socket
                // after it is closed, which means a new socket instance has to
                // be created.
                socket.close();
            }

        } catch (Exception e) {

            MyLog.e("TCP", "C: Error", e);

        }

    }

    // Declare the interface. The method messageReceived(String message) will
    // must be implemented in the MyActivity
    // class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }
}

Android Client: Constants

public class Constants {

    public static final String CLOSED_CONNECTION = "kazy_closed_connection";
    public static final String LOGIN_NAME = "kazy_login_name";

}

Android Client: My Activity

@Override
protected void onPause() {
    super.onPause();
    if(connect != null) {
        connect.cancel(true);
    }
    if(mTcpClient != null) {
        MyLog.d(TAG, "stopClient");
        mTcpClient.stopClient();
        mTcpClient = null;
    }
}

public class ConnectTask extends AsyncTask<String,String,TCPClient> {

    @Override
    protected TCPClient doInBackground(String... message) {

        MyLog.d(TAG, "doInBackground");

        //we create a TCPClient object and
        mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {

                //this method calls the onProgressUpdate
                publishProgress(message);

            }
        });
        mTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        MyLog.d(TAG, "onProgressUpdate");
        View view = adapter.getChildView(0, 0, false, null, null);
        TextView text = (TextView) view.findViewById(R.id.betChildOdd);
        child2.get(0).get(0).put("OLD", text.getText().toString());
        child2.get(0).get(0).put(CONVERTED_ODDS, values[0].toString());
        child2.get(0).get(0).put("CHANGE", "TRUE");
        adapter.notifyDataSetChanged();
    }
}

解决方案

I didn't go through all your code but the first thing that came to my mind is: did you build your application based on a multithread server architecture? For what I saw in your code, I noticed that you do not delegate the execution of what comes after the socket.accept() to another thread, that's why you are not able to answer multiple clients at the same time.

Bear in mind that you need to take care of possible race conditions generated by concurrent access to same data structures.

This is the pattern you should follow for you TCP server : http://tutorials.jenkov.com/java-multithreaded-servers/multithreaded-server.html

这篇关于Android的TCP连接(多客户端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆