TCP Server and Client

Introduction

See the code of the simple TCP server and client below. They are based on the C++ TCP example in SFML. The server accepts only the first client to connect. Typical outputs from the server and client are as follows.

Server:

Server is listening to port 1717 waiting for connections...
Client connected: 192.168.0.2
Message sent to the client: Hi, I'm the server
Answer received from the client: Hi, I'm a client

Client:

Type the address or name of the server to connect to:
192.168.0.3
Connected to server
Message received from the server: Hi, I'm the server
Message sent to the server: Hi, I'm a client

Code of Server

program ServerDemo;
uses
  SfmlNetwork;
const
  PORT = 1717;
var
  pSocket:  PsfmlTcpSocket;
  Listener: TsfmlTcpListener;
  AddressRecord: TSfmlIpAddress;
  MsgFromClient : array[0..99] of char;
  MsgSize: LongWord;
  PMsg: pointer;

procedure RunTcpServer(MyPort: integer );
const
  Msg: PChar = 'Hi, I''m the server';

begin
  Listener := TsfmlTcpListener.Create;
  // Listen to the given port for incoming connections
  if Listener.listen(MyPort) <> sfSocketDone then
    exit;
  writeln('Server is listening to port ', MyPort , ' waiting for connections... ');
  // Wait for a connection
  if Listener.accept(pSocket) <> sfSocketDone then
    exit;
  AddressRecord := SfmlTcpSocketGetRemoteAddress(psocket);
  writeln('Client connected: ', AddressRecord.Address );
  // Send a message to the connected client
  if SfmlTcpSocketSend(psocket, msg, 18) <> sfSocketDone then
    exit;
  writeln('Message sent to the client: ', msg);
  // Receive a message back from the client
  PMsg := @MsgFromClient;
  if SfmlTcpSocketReceive(pSocket, PMsg, 100, MsgSize) <> sfSocketDone then
    exit;
  writeln('Answer received from the client: ',  MsgFromClient);
end;

begin
  RunTcpServer(port);
  readln;
end.
    

Code of Client

program ClientDemo;
uses
  SfmlNetwork, SfmlSystem;
const
  PORT = 1717;
var
 ServerRecord: TsfmlIpAddress;
 Socket: TsfmlTcpSocket;
 MsgFromServer, MsgToServer : array[0..99] of char;
 PMsg: pointer;
 MsgLength: LongWord;

procedure RunTcpClient(MyPort: integer );
begin
  PMsg := @MsgFromServer;
  Socket := TsfmlTcpSocket.Create;
  writeln('Type the address or name of the server to connect to: ');
  readln (ServerRecord.Address);
  if SfmlTcpSocketConnect(Socket.Handle, ServerRecord, MyPort, SfmlSeconds(2)) <> sfSocketDone then
    exit;
  writeln('Connected to server');
  if socket.receive(PMsg, 100, MsgLength) <> sfSocketDone then
    exit;
  writeln('Message received from the server: ', MsgFromServer);
  PMsg := @MsgToServer;
  // Send an answer to the server
  MsgToServer := 'Hi, I''m a client';
  if socket.send(PMsg, 18) <> sfSocketDone then
    exit;
  writeln('Message sent to the server: ',  MsgToServer);
end;

begin
  runTcpClient(PORT);
  readln;
end.
    
Programming - a skill for life!

How to use the Simple Fast Media Library in Lazarus