The client can send messages to the server in several ways. Two methods are discussed here:
1. After the client connects to the server, it sends a stream, and the server receives a stream.
{*------------------------------------------------------------------------------
The client sends a stream, assuming a connection has been established
------------------------------------------------------------------------------*}
Procedure tclientform. button3click (Sender: tobject );
VaR S: string; stream: tstream;
Begin
Try
S: = 'Hello world! ';
Stream: = tstringstream. Create (s );
Idtcpclient1.openwritebuffer;
Idtcpclient1.writeinteger (stream. size); // Note: Write the length of the stream first. If athread. Connection. readstream (Stream) is used during reading );
Idtcpclient1.writestream (stream, true );
Finally
Idtcpclient1.closewritebuffer;
Stream. Free;
End;
End;
{*------------------------------------------------------------------------------
Server receiving stream
------------------------------------------------------------------------------*}
Procedure tserverform. idtcpserver1execute (athread: tidpeerthread );
VaR stream: tstream;
Begin
If not athread. terminated and athread. Connection. connected then
Begin
Stream: = tstringstream. Create ('');
Athread. Connection. readstream (Stream); // This sentence is equivalent to readstream (stream,-1, false). It reads the length of the stream based on the first four bytes of the stream and then reads the stream.
Stream. Position: = 0;
Memo1.lines. loadfromstream (Stream );
End;
End;
2. After the client connects to the server, it sends one or more streams. When disconnected, the server merges all the streams for receiving.
{*------------------------------------------------------------------------------
The client sends a stream. Assume that no connection has been established.
------------------------------------------------------------------------------*}
Procedure tclientform. button3click (Sender: tobject );
VaR S: string; stream: tstream;
Begin
Idtcpclient1.connect;
Try
S: = 'Hello world! ';
Stream: = tstringstream. Create (s );
Idtcpclient1.openwritebuffer;
Idtcpclient1.writestream (stream, true );
Finally
Idtcpclient1.closewritebuffer;
Stream. Free;
Idtcpclient1.disconnect;
End;
End;
{*------------------------------------------------------------------------------
Server receiving stream
------------------------------------------------------------------------------*}
Procedure tserverform. idtcpserver1execute (athread: tidpeerthread );
VaR stream: tstream;
Begin
If not athread. terminated and athread. Connection. connected then
Begin
Stream: = tstringstream. Create ('');
Athread. Connection. readstream (stream,-1, true); // receives the stream when the connection is disconnected.
Stream. Position: = 0;
Memo1.lines. loadfromstream (Stream );
End;
End;