Chat Room Socket (Delphi)

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 Server.pas
    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:
      procedure TForm1.Button2Click(Sender: TObject);
      begin
         if(ServerSocket1.Active = False)//The button caption is ‘Start’
         then
         begin
            ServerSocket1.Active := True;//Activates the server socket
            Memo1.Text:=Memo1.Text+'Server Started'+#13#10;
            Button2.Caption:='Stop';//Set the button caption 
         end
         else//The button caption is ‘Stop’
         begin
            ServerSocket1.Active := False;//Stops the server socket
            Memo1.Text:=Memo1.Text+'Server Stopped'+#13#10;
            Button2.Caption:='Start';
           //If the server is closed, then it cannot send any messages
            Button1.Enabled:=false;//Disables the “Send” button
            Edit1.Enabled:=false;//Disables the edit box
         end;
      end;
      
    3. Add the code below to the OnClick event of the Send button:
      procedure TForm2.Button1Click(Sender: TObject);
      var
        i: integer;
      begin
           Str:=Edit1.Text;//Take the string (message) sent by the server
           Memo1.Text:=Memo1.Text+'me: '+Str+#13#10;//Adds the message to the memo box
           Edit1.Text:='';//Clears the edit box
      //Sends the messages to all clients connected to the server
           for i:=0 to ServerSocket1.Socket.ActiveConnections-1 do
            ServerSocket1.Socket.Connections[i].SendText(str);//Sent 
      end;
      
    4. Add the code below to the OnClientConnect event of TServerSocket:
      procedure TForm1.ServerSocket1ClientConnect(Sender: TObject;  Socket: TCustomWinSocket);
      begin
        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;
      end;
      
    5. Add the code below to the OnClientDisconnect event of TServerSocket:
      procedure TForm1.ServerSocket1ClientDisconnect(Sender: TObject;
        Socket: TCustomWinSocket);
      Begin
      //The server cannot send messages if there is no client connected to it
        if ServerSocket1.Socket.ActiveConnections-1=0 then
        begin
          Button1.Enabled:=false;
          Edit1.Enabled:=false;
        end;
      end;
      
    6. Add the code below to the OnClientRead event of TServerSocket:
      procedure TForm1.ServerSocket1ClientRead(Sender: TObject;
        Socket: TCustomWinSocket);
      Begin
      //Read the message received from the client and add it to the memo text
      // The client identifier appears in front of the message
        Memo1.Text:=Memo1.Text+'Client'+IntToStr(Socket.SocketHandle)+' :'+Socket.ReceiveText+#13#10;
      end;
      
  7. In Client.pas
    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:
      procedure TForm2.Button2Click(Sender: TObject);
      begin
      //127.0.0.1 is the standard IP address to loop back to your own machine
          ClientSocket1.Address:='127.0.0.1';
          ClientSocket1.Active := True;//Activates the client
         
       if(ClientSocket1.Socket.Connected=True)
          then
          begin
            str:='Disconnected';
            ClientSocket1.Active := False;//Disconnects the client
            Button2.Caption:='Connect';
          end;
      end;
      
    3. Add the code below to the OnClick event of the Send button:
      procedure TForm2.Button1Click(Sender: TObject);
      begin
          Str:=Edit1.Text;
          Memo1.Text:=Memo1.Text+'me: '+str+#13#10;
          Edit1.Text:='';//Clears the edit box
          ClientSocket1.Socket.SendText(str);//Send the messages to the server
      end;
      
    4. Add the code below to the OnDisconnect event of TClientSocket:
      procedure TForm2.ClientSocket1Disconnect(Sender: TObject;  Socket: TCustomWinSocket);
      begin
         Memo1.Text:=Memo1.Text+'Disconnect'+#13#10;
         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';
      end;
      
    5. Add the code below to the OnError event of TClientSocket:
      procedure TForm2.ClientSocket1Error(Sender: TObject; Socket: TCustomWinSocket;  ErrorEvent: TErrorEvent; var ErrorCode: Integer);
      begin
        ErrorCode:=0;
        ClientSocket1.Active := False;
      // This can happen when no active server is started
        Memo1.Text:=Memo1.Text+'No connection found'+#13#10;
      end;
      
    6. Add the code below to the OnRead event of TClientSocket:
      procedure TForm1.ClientSocket1Read(Sender: TObject; Socket: TCustomWinSocket);
      begin
      //Reads and displays the message received from the server;
          Memo1.Text:=Memo1.Text+'Server: '+Socket.ReceiveText+#13#10;
      end;
      

To test the example:

  1. In the Project Manager, right-click Server.exe and then press Run.
  2. Right-click Client.exe and then 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 from the client form.
  5. Start sending messages from server to client, and from client to server.

Uses

See Also