Creating Chat Application with Borland Delphi/Indy: The Client
In this third article in a series on building a chat application, you will learn how to build the user interface, how to create code to deal with messages sent from the server, how to send a request to the server, and more.
Creating Chat Application with Borland Delphi/Indy: The Client - The TLog/TReading Classes (Page 4 of 5 )
The TLog/TReading classes are the meat of this application. This is where all the commands or messages coming from the server will be read and processed. When a message arrives from the server, it is stored in the variable called AMsg, then in FMsg as above.
procedure TLog.DoSynchronize; var idx:integer; cmd,bw,fn,msg:string; FStream,fstream2: TFileStream; IdStream,idstream2: TIdStreamVCL; MStream: TMemoryStream; begin //find position of @ in FMsg //remember the message coming from server will be in format: msg/command@from:to idx:=pos('@',FMsg); //get the command cmd:=copy(FMsg,1,idx-1); //list of names recieved if cmd='list' then begin FMsg:= Copy(FMsg, Pos('@', FMsg)+1, Length(FMsg)-Pos ('@', FMsg)); form1.lnames.Clear; form1.lnames.Items.Add('***Current Members***'); //display the list of names to the listbox form1.lnames.Items.Add(FMsg); end //picture have been send else if cmd= 'pic' then begin // server sends: 'pic@'+fn+':Sending file...' parsestring(FMsg,bw,fn,msg); //read the file in and save MStream := TMemoryStream.Create; try form1.msg.Lines.Add('Recieving file ' +fn+'...'); IdStream := TIdStreamVCL.Create(MStream); try form1.tc.IOHandler.ReadStream(IdStream); //save file mstream.SaveToFile(fn); //try getting file path to indicate where saved form1.msg.Lines.Add('File successfully recieved'); finally IdStream.Free; end; finally MStream.Free; end; end else //it’s a plain message, just add to the memo Form1.msg.lines.add(FMsg); end;
In the above code, all that happens is that when the message is received, the procedure extracts the command, which would have been sent from the server. For example, if the server sends a message containing the command pic, then the client would prepare to receive a file.
class procedure TLog.AddMsg(const AMsg: String); begin with Create(AMsg) do try Synchronize; finally Free; end; end;
constructor TReadingThread.Create(AConn: TIdTCPConnection); begin FConn := AConn; inherited Create(False); end;
procedure TReadingThread.Execute; begin while not Terminated and FConn.Connected do begin // read msg from server TLog.AddMsg(FConn.IOHandler.ReadLn); end; end;
As previously stated, the three procecures above work together to receive and process the message received from the server.