Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

ServerSocket - OnClientRead event.

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
I've been reading up on some examples of how to receive data from the connection. Now, here's a snippet from one of the examples i'm looking at (this is in the Client's OnRead event using a TClientSocket:

var
MsgLen : integer;
Buf : string;
LenReceived: integer;
begin
MsgLen := Socket.ReceiveLength;
SetLength( Buf, MsgLen );
LenReceived := Socket.ReceiveBuf( Buf[1], MsgLen );
Buf := Copy( Buf, 1, LenReceived );

Could someone explain what's going on here? I'm slightly confuse as to what's happening and i'm fairly new to Delphi so a simple explanation would be great.



 
MsgLen := Socket.ReceiveLength;

Socket is a parameter of the procedure we're inside; mysocketRead or whatever. That Socket is a TClientWinSocket object, with properties, methods and all; and we're accessing this TClientWinSocket object's ReceiveLength property, to find out the length of the data we've received.

SetLength( Buf, MsgLen );

Now we want to copy the data received out, so we can use it. To do that, we're going to need a buffer big enough to put it in. So we force Delphi to size a string variable to the length we want.

LenReceived := Socket.ReceiveBuf( Buf[1], MsgLen );

Next, we call the socket object's ReceiveBuf method. Looking this up in help, we see that ReceiveBuf is a function. We pass it a buffer, and a number which is the length of that buffer. This is handy because maybe while we were processing the last two lines of code, more data arrived at the socket. This way, our buffer won't be overrun. ReceiveBuf, says the help, returns the length of data that it has actually copied into your buffer.

Buf := Copy( Buf, 1, LenReceived );

So, just in case our buffer was 80 characters long and for some bizzarre reason ReceiveBuf only gave us 40 bytes of data, this line throws away the excess length. See the Copy function in help.

Note that the nice Delphi VCL classes you're using for this socket stuff only work for TCP. If you want to do UDP, you have to go direct to the Windows API calls, which are somewhat grungier. -- Doug Burbidge mailto:doug@ultrazone.com
 
Ahh.. that's genius rONIN441, you've really cleared that up. Thanks :).
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top