Chat Room Socket (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example builds a Chat Room using sockets components. To build the example, follow the instructions:

  1. Install the socket components.
  2. Create a VCL Forms Application and save it as Server.
  3. In the Project Manager, right-click ProjectGroup1 > Add New Project and add a new VCL Forms Application. Save it as Client.
  4. Add two buttons (Send and Start/Stop), a memo box, an edit box, and a TServerSocket from the Tool Palette to the Server form.
  5. Add two buttons (Send and Connect/Disconnect), a memo box, an edit box, and a TClientSocket from the Tool Palette to the Client form.

    Code

  6. In Unit1.cpp (Server methods):
    1. Add to the TForm1 class a private variable, Str, of type String, in which to save the messages received or sent by the server.
    2. Add the code below to the OnClick event of the Start button:
      void __fastcall TForm1::Button2Click(TObject *Sender)
      {
         if (ServerSocket1->Active==false)//The button caption is ‘Start’
         {
      		ServerSocket1->Active=true;//Activates the server socket
      		Memo1->Text=Memo1->Text+ "Server Strated\r\n";
      		Button2->Caption="Stop";//Set the button caption
         }
         else
         {
      	   ServerSocket1->Active=false;//Stops the server socket
      	   Memo1->Text=Memo1->Text+"Server Stoped\r\n";
      	   Button2->Caption="Start";
                 //If the server is closed, then it cannot send any messages
      	   Button1->Enabled=false;//Disable the “Send” button	
      	   Edit1->Enabled=false;//Disable the edit box
         }
      }
      
    3. Add the code below to the OnClick event of the Send button:
      void __fastcall TForm1::Button1Click(TObject *Sender)
      {
      	int i;
      	Str =Edit1->Text; //Take the string (message) sent by the server
      	Memo1->Text=Memo1->Text+"me : "+ Str+ "\r\n";//Adds the message to the memo box
      	Edit1->Text=" ";//Clears the edit box
      	for (i = 0; i < ServerSocket1->Socket->ActiveConnections; i++)
      	{
      		ServerSocket1->Socket->Connections[i]->SendText(Str); //Sent
      	}
      
      }
      
    4. Add the code below to the OnClientConnect event of TServerSocket:
      void __fastcall TForm1::ServerSocket1ClientConnect(TObject *Sender, TCustomWinSocket *Socket)
      {
      	Socket->SendText("Connected");//Sends a message to the client
      	//If at least a client is connected to the server, then the server can communicate
      	//Enables the Send button and the edit box
      	Button1->Enabled=true;
      	Edit1->Enabled=true;
      }
      
    5. Add the code below to the OnClientDisconnect event of TServerSocket:
      void __fastcall TForm1::ServerSocket1ClientDisconnect(TObject *Sender, TCustomWinSocket *Socket)
      {
      //The server cannot send messages if there is no client connected to it
      	if (ServerSocket1->Socket->ActiveConnections-1==0)
      	{
      		Button1->Enabled=false;
      		Edit1->Enabled=false;
      	}
      
      }
      
    6. Add the code below to the OnClientRead event of TServerSocket:
      void __fastcall TForm1::ServerSocket1ClientRead(TObject *Sender, TCustomWinSocket *Socket)
      {
      	//Read the message received from the client and add it to the memo text
      	//The client identifier appears in front of the message 
      	char str[256];
      	itoa(Socket->SocketHandle,str,10);
      	Memo1->Text=Memo1->Text+"Client"+ str +" :"+Socket->ReceiveText()+ "\r\n";
      
      }
      
  7. In Unit2.cpp (Client methods):
    1. Add to the TForm2 class a private variable, Str, of type String, in which to save the messages received or sent by the client.
    2. Add the code below to the OnClick event of the Connect button:
      void __fastcall TForm2::Button2Click(TObject *Sender)
      {
      	//127.0.0.1 is the standard IP address to loop back to your own machine
      	ClientSocket1->Address="127.0.0.1"; //Activates the client
      	ClientSocket1->Active=true;
      	if (ClientSocket1->Socket->Connected==true)
      	{
      	   Str="Disconnected";
      	   ClientSocket1->Active=false; //Disconnects the client
      	   Button2->Caption="Connect";
      	}
      }
      
    3. Add the code below to the OnClick event of the Send button:
      void __fastcall TForm2::Button1Click(TObject *Sender)
      {
         Str=Edit1->Text;
         Memo1->Text=Memo1->Text+"me: "+Str+"\r\n";
         Edit1->Text=" ";//Clears the edit box
         ClientSocket1->Socket->SendText(Str); //Send the messages to the server
      }
      
    4. Add the code below to the OnDisconnect event of TClientSocket:
      void __fastcall TForm2::ClientSocket1Disconnect(TObject *Sender, TCustomWinSocket *Socket)
      {
      	Memo1->Text=Memo1->Text+"Disconnect\r\n";
      	Socket->SendText(Str);//Send the “Disconnected” message to the server
      	//str is set to “Disconnected” when the Disconnect button is pressed
      	//A client cannot send messages if it is not connected to a server
      	Button1->Enabled=False;
      	Edit1->Enabled=False;
      	Button2->Caption="Connect";
      
      }
      
    5. Add the code below to the OnError event of TClientSocket:
      void __fastcall TForm2::ClientSocket1Error(TObject *Sender, TCustomWinSocket *Socket, TErrorEvent ErrorEvent, int &ErrorCode)
      {
      	ErrorCode=0;
      	ClientSocket1->Active = false;
      	// This can happen when no active server is started
      	Memo1->Text=Memo1->Text+"No connection found\r\n";
      }
      
    6. Add the code below to the OnRead event of the TClientSocket:
      void __fastcall TForm2::ClientSocket1Read(TObject *Sender, TCustomWinSocket *Socket)
      {
      	//Reads and displays the message received from the server
      	Memo1->Text=Memo1->Text+"Server: "+Socket->ReceiveText()+"\r\n";
      }
      

To test the example:

  1. In the Project Manager, right-click Server.exe and then press Run.
  2. Right-click Client.exe and select Run without debugging.
  3. Start the Server by pressing the Start button from the server form.
  4. Connect the Client by pressing the Connect button of the client form.
  5. Start sending messages from server to client, and from client to server.

Uses

See Also