3

我正在编写一个实时支持聊天在这里,但我面临的问题是我制作的这个服务器如何只接收一个客户端来聊天。

任何专业人士可以向我解释让服务器同时接收多个客户端吗?

还有另一个问题是:如果我关闭聊天活动,然后通过应用程序回来进行新的聊天,服务器无法响应。

有什么建议请...

服务器端:

public class TCPServer extends Thread {

public static final int SERVERPORT = 7777;
private boolean running = false;
private PrintWriter mOut;
private OnMessageReceived messageListener;

public static void main(String[] args) {

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

}

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


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

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


    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 serverSocket = new ServerSocket(SERVERPORT);

        //create client socket... the method accept() listens for a connection to be made to this socket and accepts it.
        Socket client = serverSocket.accept();
        System.out.println("S: Receiving...");

        try {

            //sends the message to the client
            mOut = 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 = in.readLine();

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

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

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

}


//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);
}

}

对于客户,我将它们分为两个活动:

public class TCPMainActivity extends Activity
{
private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.tcpmain);

    arrayList = new ArrayList<String>();

    final EditText editText = (EditText) findViewById(R.id.editText);
    Button send = (Button)findViewById(R.id.send_button);

    //relate the listView from java to the one created in xml
    mList = (ListView)findViewById(R.id.list);
    mAdapter = new MyCustomAdapter(this, arrayList);
    mList.setAdapter(mAdapter);

    // connect to the server
    new connectTask().execute("");

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String message = editText.getText().toString();

            //add the text in the arrayList
            arrayList.add("Student: " + message);

            //sends the message to the server
            if (mTcpClient != null) {
                mTcpClient.sendMessage(message);
            }

            //refresh the list
            mAdapter.notifyDataSetChanged();
            editText.setText("");
        }
    });

}

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

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

        //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);

        //in the arrayList we add the messaged received from server
        arrayList.add("Managment: "+values[0]);
        // notify the adapter that the data set has changed. This means that new message received
        // from server was added to the list
        mAdapter.notifyDataSetChanged();
    }
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all courses
    }

}
 protected void onStop() { // TODO Auto-generated method stub
     //mTcpClient.stopClient();
     Log.e("TCP Client", "Stooped");
     super.onStop(); 

 }

protected void onStart() { // TODO Auto-generated method stub
     super.onStart();


 }
protected void onResume() { // TODO Auto-generated method stub
 super.onResume();
 //new connectTask().execute("");
 }




    /* public void onDestroy() { // TODO Auto-generated method stub
          super.onDestroy();
     }
     */
}

第二个是:

public class TCPClient {

private String serverMessage;
public static final String SERVERIP = "192.168.0.102"; //your computer IP address
public static final int SERVERPORT = 7777;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;

PrintWriter out;
BufferedReader in;
Socket socket;

/**
 *  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 (out != null && !out.checkError()) {
        out.println(message);
        out.flush();
    }
}

public void stopClient(){
    mRun = false;
    try {
        socket.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void run() {

    mRun = true;

    try {
        if (socket != null)
            socket.close();

        //here you must put your computer's IP address.
        InetAddress serverAddr = InetAddress.getByName(SERVERIP);
        Log.e("TCP Client", "C: Connecting...");

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

        try {

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

            Log.e("TCP Client", "C: Sent.");

            Log.e("TCP Client", "C: Done.");

            //receive the message which the server sends back
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

            //in this while the client listens for the messages sent by the server
            while (mRun) {
                serverMessage = in.readLine();

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

            }


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


        } catch (Exception e) {

            Log.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) {

        Log.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);
}
}

提前谢谢你。

4

0 回答 0