SoFunction
Updated on 2025-04-09

Android implements C/S chat room

The class in Java that can accept link requests from other communication entities is ServerSocket. The ServerSocket object is used to listen for Socket links from the client. If there is no link, it will wait. If a connection request is received from a client Socket, the accept() method of ServerSocket will return a Socket corresponding to the client Socket (two Sockets per TCP connection), otherwise the method will be blocked all the time and the thread will be blocked.

Server idea: The server should contain multiple threads, each Socket corresponds to one thread. This thread is responsible for reading the data of the Socket corresponding input stream (data sent from the client) and sending the read data to each Socket output stream once (the data sent by one client is "broadcast" to other clients).

Server code:

//Server main classpublic class MyServer
{
  public static List<Socket> socketList = (new ArrayList<Socket>());
  public static void main(String[] args) throws IOException
  {
    ServerSocket ss = new ServerSocket(30000);
    while (true)
    {
      //This line of code will block and will wait for someone else's connection      Socket s = ();
      (s);
      //Every time the client connects, start a ServerThread thread to serve the client      new Thread(new ServerThread(s)).start();
    }
  }
}

public class ServerThread implements Runnable
{
  //Define the socket processed by the current thread  Socket s = null;
  //The input stream corresponding to the Socket processed by this thread  BufferedReader br = null;
  public ServerThread(Socket s) throws IOException
  {
     = s;
    //Initialize the input stream corresponding to the Socket    br = new BufferedReader(new InputStreamReader(()));
  }

  @Override
  public void run()
  {
    try
    {
      String content = null;
      //Change to continuously read the data sent by the client from the Socket      while ((content = readFromClient()) != null)
      {
        //Transfer through each Socket in the socketList        //Send the read content to each socket once        for (Socket s : )
        {
          PrintStream ps = new PrintStream(());
          (content);
        }
      }
    }
    catch (IOException e)
    {
      ();
    }
  }

  //Define the method to read client data  private String readFromClient()
  {
    try
    {
      return ();
    }
    //If an exception is caught, it means that the corresponding client of the Socket has been closed    catch (IOException e)
    {
      //Delete the Socket      (s);
    }
    return null;
  }
}

Client idea: Write the data input by the user into the input stream corresponding to the Socket; enable a child thread to read the data in the input stream corresponding to the Socket (data sent from the server), and send the read data to the main thread through the Handler to update the UI.

//User Interface Activitypublic class MainActivity extends Activity
{
  private EditText mReceiverMsg;
  private Button mSendBtn;
  private EditText mSendMsg;
  Handler handler = new Handler()
  {
    @Override
    public void handleMessage(Message msg)
    {
      ("mainActivity" , "okk");
      (());
    }
  };
  private Socket s;
  @Override
  protected void onCreate(Bundle savedInstanceState)
  {
    (savedInstanceState);
    setContentView(.main_activity);

    initView();
    initSocket();
    (new ()
    {
      @Override
      public void onClick(View view)
      {
        sendData();
      }
    });
  }

  private void initSocket()
  {
    new Thread()
    {
      @Override
      public void run()
      {
        try
        {
          s = new Socket("192.168.1.101" , 30000);
          new Thread(new ClientThread(s , handler)).start();
        }
        catch (IOException e)
        {
          ();
        }
      }
    }.start();
  }

  private void initView()
  {
    mReceiverMsg = (EditText) findViewById(.receiver_message);
    mSendMsg = (EditText) findViewById(.send_message);
    mSendBtn = (Button) findViewById(.send_button);
  }

  private void sendData()
  {
    try
    {
      //Get the output stream corresponding to the Socket      PrintStream ps = new PrintStream(());
      if ((()))
      {
        (this , "Please enter information" , Toast.LENGTH_LONG).show();
        return;
      }
      (().toString());
    }
    catch (IOException e)
    {
      ();
    }
  }
}

public class ClientThread implements Runnable
{
  //The thread is responsible for processing the socket  private Socket ss;
  //The input stream corresponding to the Socket processed by this thread  BufferedReader br = null;
  Handler handler;
  public ClientThread(Socket s , Handler handler) throws IOException
  {
     = s;
     = handler;
    br = new BufferedReader(new InputStreamReader(()));
  }

  @Override
  public void run()
  {
    try
    {
      String content = null;
      while ((content = ()) != null)
      {
        Message msg = new Message();
         = content;
        (msg);
      }

    }
    catch (IOException e)
    {
      ();
    }
  }
}

First run the MyServer class in the above program, and this class is only used as a server. Start multiple emulators and run the program that installs the client as multiple clients. Then any client can enter some content through Edit. Click Send to see the content you just entered on any client.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.