The usual procedure to create a TCP server can directly be applied with
the SocketLib functions. This schema is the following one:
- 1 - create a server half-socket
- 2 - attach the half-socket to a port
- 3 - listen on this port
The SocketLib being a part of Hyperion, it can be used like any other standard library provided
with LUA (io, math, string, os, etc.) simply by calling its name with the socket.tcp()
extension for example. The following code shows how to create the TCP server.
function createTCPServer( host, port, backlog )
local tcp_server, err = socket.tcp();
if tcp_server==nil then
return nil, err;
end
tcp_server:setoption("reuseaddr", true);
local res, err = tcp_server:bind(host, port);
if res==nil then
return nil, err;
end
res, err = tcp_server:listen(backlog);
if res==nil then
return nil, err;
end
return tcp_server;
end
socket.tcp() allows to create a TCP server object. It is then possible to access
the server functions by separating the server name and the function name by 2 points: tcp_server:setoption().
A detailed explanation on functions and objects provided with the SocketLib is available in the
project at the end of this page.
All the functions used after the creation of the server object are really well known for
this kind of job: setoption(), bind() and listen().
Most of the SocketLib functions return one parameter if successful and two parameters
if not. If a failure occurs, the first returned value is nil and the second value is
the error message.
The createTCPServer() function must be called once during ths initialization of the host program.
This is done in Hyperion just by inserting both the code and the call to that function in an initialization
LUA script (run_mode="INIT").
Last thing: pay attention to the host parameter in createTCPServer() function. If you set
it with "localhost", the TCP server will accept only localhost incoming connections (i.e the
client is localized on the same computer than the server). So if you wish to be able to connect to your server from a client placed physically in another computer,
you have to set host as follow: host = "*";. It's a little trick but believe me, you may
waste much time if you don't know it!
Creating a TCP server is the easiest part. Let us tackle the hardcore one:
the acceptation and the management of the in going connections.