To read bytes from a TCP socket in Delphi, you can use various components or libraries that provide TCP/IP functionality. One of the commonly used components is the TTCPBlockSocket
from the Synapse library. Below is a basic example of reading bytes from a TCP socket using Synapse:
- Download Synapse: Download the Synapse library from its official repository on GitHub: https://github.com/synopse/mORMot.
- Add Synapse to Your Project:
- Extract the Synapse archive.
- Add the necessary Synapse units to your Delphi project.
- Example Code: Below is an example that demonstrates how to create a TCP socket, connect to a server, and read bytes from the socket.
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667unit MainUnit;interfaceusesSystem.SysUtils, System.Classes, Vcl.Forms, blcksock, synsock;typeTForm1 = class(TForm)procedure FormCreate(Sender: TObject);procedure FormDestroy(Sender: TObject);privateTCPClient: TTCPBlockSocket;procedure ConnectToServer;procedure ReadBytesFromSocket;public{ Public declarations }end;varForm1: TForm1;implementation{$R *.dfm}procedure TForm1.FormCreate(Sender: TObject);beginTCPClient := TTCPBlockSocket.Create;ConnectToServer;ReadBytesFromSocket;end;procedure TForm1.FormDestroy(Sender: TObject);beginTCPClient.Free;end;procedure TForm1.ConnectToServer;begintry// Connect to the serverTCPClient.Connect(‘127.0.0.1’, ’80’);// Handle successful connectionexcept// Handle connection errorend;end;procedure TForm1.ReadBytesFromSocket;varBuffer: TBytes;begintrySetLength(Buffer, 1024); // Set the buffer size as needed// Read bytes from the socketTCPClient.RecvBufferEx(Buffer, Length(Buffer));// Process the received bytes (example: display in a memo)Memo1.Lines.Add(‘Received Bytes: ‘ + string(TEncoding.ASCII.GetString(Buffer)));except// Handle read errorend;end;end.
In this example:ConnectToServer
connects to a server (adjust the IP address and port as needed).ReadBytesFromSocket
reads bytes from the connected socket and displays them in a memo.
Make sure to handle exceptions appropriately and adjust the code based on your specific requirements. The example assumes that the server is running on the localhost (127.0.0.1) and the port is 80. Modify these values based on your server configuration.
Always check the documentation of the libraries you use and ensure compatibility with your Delphi version.
Leave a Reply