This demo demonstrates how to directly transfer tstream objects between the client and the server, so that you can focus on data processing logic and ignore the problem of handling inter-network packets.
The server pushes a message tmemorystream object to all clients (this object is string data ).
Code explanation:
Procedure tfrmmain. actpushmsgexecute (Sender: tobject); var lvlist: tlist; I: integer; lvstream: tmemorystream; s: ansistring; begin lvlist: = tlist. create; try lvstream: = tmemorystream. create; Try S: = edtmsg. text; lvstream. write (s [1], length (s); // obtain the list of all online clients, ftcpserver. getonlinecontextlist (lvlist); // push to all clients cyclically
For I: = 0 to lvlist. Count-1 do begin // directly push tmemorystream object <internal trial encoder encodes tstream into protocol format, and then sends>
TIOCPClientContext(lvList[i]).writeObject(lvStream); end; finally lvStream.Free; end; finally lvList.Free; end;end;
The above code is the push button
constructor TfrmMain.Create(AOwner: TComponent);begin inherited Create(AOwner); FTcpServer := TIOCPConsole.Create(Self); FTcpServer.createDataMonitor; FTcpServer.OnDataObjectReceived := OnRecvObject; // register decoder and encoder class FTcpServer.registerCoderClass(TIOCPStreamDecoder, TIOCPStreamEncoder); TFMMonitor.createAsChild(pnlMonitor, FTcpServer);end;
The above code and decoder are registered to process the conversion of objects when receiving and sending data, and receive object events are assigned a value.
Onrecvobject. If an object is decoded successfully, an event is triggered.
procedure TfrmMain.OnRecvObject(pvClientContext: TIocpClientContext; pvObject: TObject);begin pvClientContext.writeObject(pvObject);end;
// The above Code directly pushes the object back to the client.
The client code is similar. You can download socket-coder \ streamcoder to view the complete source code.