Sign in Join
Wiki copytemporary

Networking: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Networking

OldNewLine
1+This page contains both tutorials/code and information with regard to network programming with Lazarus as well as plain FPC.
2+
3+## TCP/IP Protocol
4+
5+> **Note:** Because there are multiple libraries (Synapse, lnet, fphttpclient, Indy,...) that provide networking functionality for FPC/Lazarus, many examples can be written for multiple libraries. Therefore you may see the same examples multiple times - for different libraries. Have a look at the [[Brook for Free Pascal]] or [[fpctwit]] frameworks for examples on how to build frameworks that can use multiple network libraries
6+
7+### Basic IP socket programming and a bit more
8+
9+For very basic applications and first steps exploring TCP socket communication the [[fcl-net]] library may be the best approach. It is included in the default installation. Code samples, which also serve as documentation, can be found in the ...\fpc\\...\source\packages\fcl-net\examples subdirectory of your local Lazarus installation. Amongst others there are basic TCP socket server and client implementations, and a DNS resolver. All samples are command-line only, and should work on all platforms which provide a socket-style networking interface.
10+
11+The next advanced library, and the most basic one providing GUI support, is [[lNet]] (note: the first letter is a lowercase l, for "lightweight"). If you are using the [[Lazarus Tutorial|Lazarus IDE]], you can install the latest version via the Online Package Manager (OPM). Otherwise, and for access to the latest version as well as to documentations and sample code files, see the component GIT repository hosted on [GitHub](https://github.com/almindor/lnet). A very good place to start exploring is the tcpudp demo contained in the ...\examples\visual directory. It shows a lightweight example of how to program an event-driven IP socket client and server, both blended together in one GUI program (use the "Host" button to switch between server and client mode). It also lets you play with some useful options like switching the transport protocols between TCP, UDP, IPV4 and IPV6 and turning on/off basic support for SSL.
12+
13+Both fcl-net and lNet encapsulate the platform dependent socket libraries to provide a cross-platform interface for all platforms supported by FPC/Lazarus. The code samples contain very basic applications like Telnet, FTP, SMTP and even some very basic HTTP servers. They do not cover advanced protocols requiring authentication and/or encryption beyond basic SSL, nor do they have support for the many subprotocols and features required to build full fledged web programs. This is where more extensives libraries like fcl-web, Synapse or Brook Framework shine - see below.
14+
15+### CGI/FastCGI - REST, chat, blog, web page etc.
16+
17+These functionalities can be used with [[fcl-web]]. They are also built into the Brook framework. Please have a look at [this page](http://silvioprog.github.io/brookframework). <https://github.com/silvioprog/brookframework>
18+
19+### SSH/Telnet client, sending emails, downloading files, OAuthv1 examples
20+
21+See the [[Synapse]] page.
22+
23+### Webserver example
24+
25+Given below is an example http server written with [[Synapse]] and tested in Win XP and macOS, after changing the Synapse source to use a fixed constant \$20000 as MSG_NOSIGNAL, because this constant isn't present in the sockets unit in macOS. *Note: please send your bug reports to the Synapse project - they are quite responsive - so everybody profits from improvements. To do: check if this modification is still needed for current (Oct 2012) Synapse*
26+
27+``` pascal
28+{
29+ The Micro Pascal WebServer
30+
31+ This is a very simple example webserver implemented with the Synapse library.
32+
33+ It works with blocking sockets and a single thread, so it
34+ can only handle one request at a given time.
35+
36+ It will write the headers that it receives from the browser
37+ to the standard output.
38+
39+ It serves a fixed webpage for the / URI
40+ For any other URI it will return 404 not found
41+}
42+
43+program upserver;
44+
45+{$ifdef fpc}
46+ {$mode delphi}
47+{$endif}
48+
49+{$apptype console}
50+
51+uses
52+ Classes, blcksock, sockets, Synautil, SysUtils;
53+
54+{@@
55+ Attends a connection. Reads the headers and gives an
56+ appropriate response
57+}
58+
59+procedure AttendConnection(ASocket: TTCPBlockSocket);
60+var
61+ timeout: integer;
62+ s: string;
63+ method, uri, protocol: string;
64+ OutputDataString: string;
65+ ResultCode: integer;
66+begin
67+ timeout := 120000;
68+
69+ WriteLn('Received headers+document from browser:');
70+
71+ //read request line
72+ s := ASocket.RecvString(timeout);
73+ WriteLn(s);
74+ method := fetch(s, ' ');
75+ uri := fetch(s, ' ');
76+ protocol := fetch(s, ' ');
77+
78+ //read request headers
79+ repeat
80+ s := ASocket.RecvString(Timeout);
81+ WriteLn(s);
82+ until s = '';
83+
84+ // Now write the document to the output stream
85+
86+ if uri = '/' then
87+ begin
88+
89+ // Write the output document to the stream
90+ OutputDataString :=
91+ '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"'
92+ + ' "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + CRLF
93+ + '<html><h1>Teste</h1></html>' + CRLF;
94+
95+ // Write the headers back to the client
96+ ASocket.SendString('HTTP/1.0 200' + CRLF);
97+ ASocket.SendString('Content-type: Text/Html' + CRLF);
98+ ASocket.SendString('Content-length: ' + IntTostr(Length(OutputDataString)) + CRLF);
99+ ASocket.SendString('Connection: close' + CRLF);
100+ ASocket.SendString('Date: ' + Rfc822DateTime(now) + CRLF);
101+ ASocket.SendString('Server: Servidor do Felipe usando Synapse' + CRLF);
102+ ASocket.SendString('' + CRLF);
103+
104+ // if ASocket.lasterror <> 0 then HandleError;
105+
106+ // Write the document back to the browser
107+ ASocket.SendString(OutputDataString);
108+ end
109+ else
110+ ASocket.SendString('HTTP/1.0 404' + CRLF);
111+end;
112+
113+var
114+ ListenerSocket, ConnectionSocket: TTCPBlockSocket;
115+
116+begin
117+ ListenerSocket := TTCPBlockSocket.Create;
118+ ConnectionSocket := TTCPBlockSocket.Create;
119+
120+ ListenerSocket.CreateSocket;
121+ ListenerSocket.setLinger(true,10);
122+ ListenerSocket.bind('0.0.0.0','1500');
123+ ListenerSocket.listen;
124+
125+ repeat
126+ if ListenerSocket.canread(1000) then
127+ begin
128+ ConnectionSocket.Socket := ListenerSocket.accept;
129+ WriteLn('Attending Connection. Error code (0=Success): ', ConnectionSocket.lasterror);
130+ AttendConnection(ConnectionSocket);
131+ ConnectionSocket.CloseSocket;
132+ end;
133+ until false;
134+
135+ ListenerSocket.Free;
136+ ConnectionSocket.Free;
137+end.
138+```
139+
140+### Download HTTP page body, web server upload using POST, get external IP address
141+
142+These examples (using the FPC/Lazarus built in fphttpclient) can be found at [[fphttpclient|fphttpclient#Examples]]
143+
144+### LazWebsockets
145+
146+A WebSocket is a persistent connection between a client and server. WebSockets provide a bidirectional, full-duplex communications channel that operates over HTTP through a single TCP/IP socket connection. At its core, the WebSocket protocol facilitates message passing between a client and server. [LazWebsockets](https://github.com/Warfley/LazWebsockets) provides a small Websocket server and client implementation written for the FPC and Lazarus. It is based on the FCL ssockets unit and therefore independent of any additional dependencies. It can be easily built using only the FPC without Lazarus. There is a chat server and chat client example demo.
147+
148+## Web Services
149+
150+According to the [W3C](http://www.w3.org/) a Web service is a software system designed to support interoperable machine-to-machine interaction over a network. It has an interface that is described in a machine-processable format such as WSDL. Other systems interact with the Web service in a manner prescribed by its interface using messages, which may be enclosed in a SOAP envelope, or follow a REST approach. These messages are typically conveyed using HTTP, and are normally comprised of XML in conjunction with other Web-related standards. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Windows and Linux applications) is due to the use of open standards. OASIS and the W3C are the primary committees responsible for the architecture and standardization of web services. To improve interoperability between web service implementations, the WS-I organisation has been developing a series of profiles to further define the standards involved.
151+
152+### RSS example
153+
154+For an RSS example, see this article [[RSS|RSS Unit]].
155+
156+### Web Service Toolkit for FPC & Lazarus
157+
158+[[Web Service Toolkit]] is a web services package for FPC and Lazarus.
159+
160+### Using Google Translate
161+
162+For an example of using the Google translation service, see the article [[Using Google Translate]] which employs the [[fphttpclient]] component from the [[fcl-web]] package.
163+
164+## See also
165+
166+- [[Portal:Web Development|Web Development Portal]]
167+- [[Brook for Free Pascal]] - The perfect Free Pascal framework for your web applications. It's pure Pascal. You don't need to leave your preferred programming language.
168+- [[fcl-net]] - Networking library supplied with FPC
169+- [[fcl-web]] - Also known as fpWeb, this is a library to develop web applications which can be deployed as cgi, fastcgi or apache modules.
170+- [[fpbrowser]] - web browser written in FPC + Lazarus.
171+- [[Indy with Lazarus]] - Networking Components; How to install
172+- [[Internet Tools]] - A wrapper around Synapse/WinInet/Android's HTTP components simplifying HTTPS and redirections, and a XPath/XQuery/CSS Selector/JSONiq engine to process the downloaded pages
173+- [[FPC and Apache Modules]]
174+- [[lNet]] - Lightweight Networking Components
175+- [[Networking libraries]] - comparison of various networking libraries
176+- [[OpenURL]] - opens a URL with the default/registered/preferred web browser as specified by the operating system.
177+- [[Secure programming|Secure Programming]]
178+- [[Sockets]] - TCP/IP Sockets components
179+- [[Synapse]] - Serial port and synchronous TCP/IP Library
180+- [[XML Tutorial]] - XML is often utilized on network communications
181+
182+### macOS
183+
184+- [[macOS NSURLConnection]] This API lets you load the contents of a URL via HTTP and HTTPS by providing a URL request object.
185+- [[macOS NSURLSession]] This class and related classes provide an API for downloading content via HTTP and HTTPS.
186+- [[macOS Open Sesame|macOS open command]] Opens a URL in the default web browser.
187+
188+### Windows
189+
190+- [[Windows Programming Tips|WinInet]] (Windows Internet) API enables your application to interact with FTP and HTTP protocols to access Internet resources.
191+
192+## External links
193+
194+- [Fano Framework](https://fanoframework.github.io) - Web application framework written in Free Pascal.
195+- [FastPlaz](http://www.fastplaz.com) - Fast Web Framework for pascal. More features like theme/templating, simple Model, session, mailer, etc.
196+
197+---
198+*From the Free Pascal wiki, page "Networking", as it stood on 2022-01-24 after a change by ArminLinder, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*

Back to history