* Added enet library headers (+ sample programs), bug ID #27891

git-svn-id: trunk@30645 -
This commit is contained in:
michael 2015-04-18 11:10:38 +00:00
parent 3ce29dcfb2
commit a8b8f4463c
18 changed files with 4489 additions and 0 deletions

15
.gitattributes vendored
View File

@ -4785,6 +4785,21 @@ packages/libcurl/examples/testcurl.pp svneol=native#text/plain
packages/libcurl/examples/teststream.pp svneol=native#text/plain
packages/libcurl/fpmake.pp svneol=native#text/plain
packages/libcurl/src/libcurl.pp svneol=native#text/plain
packages/libenet/Makefile svneol=native#text/plain
packages/libenet/Makefile.fpc svneol=native#text/plain
packages/libenet/examples/clientapp.lpi svneol=native#text/plain
packages/libenet/examples/clientapp.pp svneol=native#text/plain
packages/libenet/examples/serverapp.lpi svneol=native#text/plain
packages/libenet/examples/serverapp.pp svneol=native#text/plain
packages/libenet/fpmake.pp svneol=native#text/plain
packages/libenet/src/enet.pp svneol=native#text/plain
packages/libenet/src/enetcallbacks.pp svneol=native#text/plain
packages/libenet/src/enetlist.pp svneol=native#text/plain
packages/libenet/src/enetplatform.pp svneol=native#text/plain
packages/libenet/src/enetprotocol.pp svneol=native#text/plain
packages/libenet/src/enettime.pp svneol=native#text/plain
packages/libenet/src/enettypes.pp svneol=native#text/plain
packages/libenet/src/uenetclass.pp svneol=native#text/plain
packages/libgbafpc/Makefile svneol=native#text/plain
packages/libgbafpc/Makefile.fpc svneol=native#text/plain
packages/libgbafpc/Makefile.fpc.fpcmake svneol=native#text/plain

View File

@ -122,4 +122,5 @@
add_x11(ADirectory+IncludeTrailingPathDelimiter('x11'));
add_xforms(ADirectory+IncludeTrailingPathDelimiter('xforms'));
add_zlib(ADirectory+IncludeTrailingPathDelimiter('zlib'));
add_libenet(ADirectory+IncludeTrailingPathDelimiter('libenet'));
add_zorba(ADirectory+IncludeTrailingPathDelimiter('zorba'));

View File

@ -706,6 +706,12 @@ begin
{$include zlib/fpmake.pp}
end;
procedure add_libenet(const ADirectory: string);
begin
with Installer do
{$include libenet/fpmake.pp}
end;
procedure add_zorba(const ADirectory: string);
begin
with Installer do

2540
packages/libenet/Makefile Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,100 @@
#
# Makefile.fpc for running fpmake
#
[package]
name=libenet
version=3.1.1
[require]
packages=rtl rtl-objpas fpmkunit
[install]
fpcpackage=y
[default]
fpcdir=../..
[prerules]
FPMAKE_BIN_CLEAN=$(wildcard ./fpmake$(SRCEXEEXT))
ifdef OS_TARGET
FPC_TARGETOPT+=--os=$(OS_TARGET)
endif
ifdef CPU_TARGET
FPC_TARGETOPT+=--cpu=$(CPU_TARGET)
endif
LOCALFPMAKE=./fpmake$(SRCEXEEXT)
[rules]
# Do not pass the Makefile's unit and binary target locations. fpmake uses it's own.
override FPCOPT:=$(filter-out -FU%,$(FPCOPT))
override FPCOPT:=$(filter-out -FE%,$(FPCOPT))
# Compose general fpmake-parameters
ifdef FPMAKEOPT
FPMAKE_OPT+=$(FPMAKEOPT)
endif
FPMAKE_OPT+=--localunitdir=../..
FPMAKE_OPT+=--globalunitdir=..
FPMAKE_OPT+=$(FPC_TARGETOPT)
FPMAKE_OPT+=$(addprefix -o ,$(FPCOPT))
FPMAKE_OPT+=--compiler=$(FPC)
FPMAKE_OPT+=-bu
.NOTPARALLEL:
fpmake$(SRCEXEEXT): fpmake.pp
$(FPCFPMAKE) fpmake.pp $(FPMAKE_SKIP_CONFIG) $(addprefix -Fu,$(COMPILER_FPMAKE_UNITDIR)) $(FPCMAKEOPT) $(OPT)
all: fpmake$(SRCEXEEXT)
$(LOCALFPMAKE) compile $(FPMAKE_OPT)
smart: fpmake$(SRCEXEEXT)
$(LOCALFPMAKE) compile $(FPMAKE_OPT) -o -XX -o -CX
release: fpmake$(SRCEXEEXT)
$(LOCALFPMAKE) compile $(FPMAKE_OPT) -o -dRELEASE
debug: fpmake$(SRCEXEEXT)
$(LOCALFPMAKE) compile $(FPMAKE_OPT) -o -dDEBUG
# If no fpmake exists and (dist)clean is called, do not try to build fpmake, it will
# most often fail because the dependencies are cleared.
# In case of a clean, simply do nothing
ifeq ($(FPMAKE_BIN_CLEAN),)
clean:
else
clean:
$(FPMAKE_BIN_CLEAN) clean $(FPMAKE_OPT)
endif
# In case of a distclean, perform an 'old'-style distclean. This to avoid problems
# when the package is compiled using fpcmake prior to running this clean using fpmake
ifeq ($(FPMAKE_BIN_CLEAN),)
distclean: $(addsuffix _distclean,$(TARGET_DIRS)) fpc_cleanall
else
distclean:
ifdef inUnix
{ $(FPMAKE_BIN_CLEAN) distclean $(FPMAKE_OPT); if [ $$? != "0" ]; then { echo Something wrong with fpmake exectable. Remove the executable and call make recursively to recover.; $(DEL) $(FPMAKE_BIN_CLEAN); $(MAKE) fpc_cleanall; }; fi; }
else
$(FPMAKE_BIN_CLEAN) distclean $(FPMAKE_OPT)
endif
-$(DEL) $(LOCALFPMAKE)
endif
cleanall: distclean
install: fpmake$(SRCEXEEXT)
ifdef UNIXHier
$(LOCALFPMAKE) install $(FPMAKE_OPT) --prefix=$(INSTALL_PREFIX) --baseinstalldir=$(INSTALL_LIBDIR)/fpc/$(FPC_VERSION) --unitinstalldir=$(INSTALL_UNITDIR)
else
$(LOCALFPMAKE) install $(FPMAKE_OPT) --prefix=$(INSTALL_BASEDIR) --baseinstalldir=$(INSTALL_BASEDIR) --unitinstalldir=$(INSTALL_UNITDIR)
endif
# distinstall also installs the example-sources and omits the location of the source-
# files from the fpunits.cfg files.
distinstall: fpmake$(SRCEXEEXT)
ifdef UNIXHier
$(LOCALFPMAKE) install $(FPMAKE_OPT) --prefix=$(INSTALL_PREFIX) --baseinstalldir=$(INSTALL_LIBDIR)/fpc/$(FPC_VERSION) --unitinstalldir=$(INSTALL_UNITDIR) -ie -fsp 0
else
$(LOCALFPMAKE) install $(FPMAKE_OPT) --prefix=$(INSTALL_BASEDIR) --baseinstalldir=$(INSTALL_BASEDIR) --unitinstalldir=$(INSTALL_UNITDIR) -ie -fsp 0
endif
zipinstall: fpmake$(SRCEXEEXT)
$(LOCALFPMAKE) zipinstall $(FPMAKE_OPT) --zipprefix=$(DIST_DESTDIR)/$(ZIPPREFIX)
zipdistinstall: fpmake$(SRCEXEEXT)
$(LOCALFPMAKE) zipinstall $(FPMAKE_OPT) --zipprefix=$(DIST_DESTDIR)/$(ZIPPREFIX) -ie -fsp 0
zipsourceinstall: fpmake$(SRCEXEEXT)
ifdef UNIXHier
$(LOCALFPMAKE) archive $(FPMAKE_OPT) --zipprefix=$(DIST_DESTDIR)/$(ZIPPREFIX) --prefix=share/src/fpc-\$$\(PACKAGEVERSION\)/$(INSTALL_FPCSUBDIR)/\$$\(PACKAGEDIRECTORY\)
else
$(LOCALFPMAKE) archive $(FPMAKE_OPT) --zipprefix=$(DIST_DESTDIR)/$(ZIPPREFIX) --prefix=source\\$(INSTALL_FPCSUBDIR)\\\$$\(PACKAGEDIRECTORY\)
endif

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectOptions>
<Version Value="9"/>
<General>
<Flags>
<MainUnitHasCreateFormStatements Value="False"/>
<MainUnitHasTitleStatement Value="False"/>
</Flags>
<SessionStorage Value="InProjectDir"/>
<MainUnit Value="0"/>
<Title Value="clientapp"/>
<UseAppBundle Value="False"/>
<ResourceType Value="res"/>
</General>
<i18n>
<EnableI18N LFM="False"/>
</i18n>
<VersionInfo>
<StringTable ProductVersion=""/>
</VersionInfo>
<BuildModes Count="1">
<Item1 Name="Default" Default="True"/>
</BuildModes>
<PublishOptions>
<Version Value="2"/>
</PublishOptions>
<RunParams>
<local>
<FormatVersion Value="1"/>
</local>
</RunParams>
<Units Count="1">
<Unit0>
<Filename Value="clientapp.pp"/>
<IsPartOfProject Value="True"/>
<UnitName Value="clientapp"/>
</Unit0>
</Units>
</ProjectOptions>
<CompilerOptions>
<Version Value="11"/>
<Target>
<Filename Value="clientapp"/>
</Target>
<Parsing>
<SyntaxOptions>
<UseAnsiStrings Value="False"/>
</SyntaxOptions>
</Parsing>
</CompilerOptions>
<Debugging>
<Exceptions Count="3">
<Item1>
<Name Value="EAbort"/>
</Item1>
<Item2>
<Name Value="ECodetoolError"/>
</Item2>
<Item3>
<Name Value="EFOpenError"/>
</Item3>
</Exceptions>
</Debugging>
</CONFIG>

View File

@ -0,0 +1,154 @@
program clientapp;
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
{$mode objfpc}{$H+}
uses
custapp, Classes, SysUtils, enet, uenetclass;
type
{ TClientApplication }
TClientApplication = class(TCustomApplication)
Private
myClient: TENetClass;
procedure DoConnect;
procedure OnConnect(const Event:ENetEvent);
procedure OnReceive(const Event:ENetEvent; var BroadcastMsg : Boolean; var BroadcastChannel : Byte);
procedure ProcessLoop;
procedure SendMessage(AMessage: String);
procedure WriteHelp;
Protected
Procedure DoRun; override;
public
Constructor Create(AOWner : TComponent); override;
Destructor Destroy; override;
end;
Var
Application : TClientApplication;
constructor TClientApplication.Create(AOWner: TComponent);
begin
INherited;
StopOnException:=True;
myClient := TENetClass.Create(30000,False);
myClient.MessageTimeout:=100;
myClient.OnReceive:=@OnReceive;
myClient.OnConnect:=@OnConnect;
myClient.OnDisconnect:=@OnConnect;
end;
destructor TClientApplication.Destroy;
begin
myClient.Free;
Inherited;
end;
procedure TClientApplication.SendMessage(AMessage : String);
begin
myClient.BroadcastMsg(1,PChar(AMessage),Length(AMessage)+1,[ENetPacketReliable]);
end;
procedure TClientApplication.ProcessLoop;
begin
myClient.ProcessMsg;
end;
procedure TClientApplication.DoConnect;
Var
H : String;
P : Integer;
begin
H:=GetOptionValue('H','host');
if (H='') then
H:='localhost';
P:=StrToIntDef(GetOptionValue('p','port'),0);
if P=0 then
P:=30000;
myClient.Connect(H,P);
end;
procedure TClientApplication.OnConnect(const Event: ENetEvent);
begin
if Event.kind=ENET_EVENT_TYPE_CONNECT then
Writeln('Connected')
else
Writeln('Disconnected');
end;
procedure TClientApplication.OnReceive(const Event: ENetEvent; var BroadcastMsg: Boolean;
var BroadcastChannel: Byte);
var
msg : string;
begin
msg := StrPas(PChar(Event.packet^.data));
Writeln('Received : "',Msg,'"');
end;
procedure TClientApplication.WriteHelp;
begin
Writeln('Usage ',ExtractFileName(Self.ExeName),' [options]');
Writeln('Where options is one or more of');
Writeln('-h --help This message');
Writeln('-H --host=hostname Hostname to connect to (default : localhost)');
Writeln('-p --port=portno Port to connect to (default 30000)');
Writeln('-p --port=portno Port to connect to (default 30000)');
Writeln('-m --message=msg Message to send to server (none means no message is sent)');
Writeln('-c --messagecount=N Number of times the message should be sent');
Writeln('-p --pingcout=N Number of times the server should be pinged. (default 0)');
Writeln('-c --messagecount=N Number of times the message should be sent (default 1)');
end;
procedure TClientApplication.DoRun;
Var
I,PingCount,MessageCount : Integer;
Msg : String;
begin
if HasOption('h','help') then
begin
WriteHelp;
Terminate;
exit;
end;
DoConnect;
PingCount:=StrToIntDef(GetOptionValue('p','pingcount'),0);
if PingCount>0 then
begin
Writeln('Pinging server');
For I:=1 to PingCount do
begin
myClient.Ping;
ProcessLoop;
end;
end;
Msg:=GetOptionValue('m','message');
if (Msg<>'') then
begin
MessageCount:=StrToIntDef(GetOptionValue('c','messagecount'),1);
Writeln('Sending message to server (count:',MessageCount,')');
For I:=1 to MessageCount do
begin
SendMessage(Msg+' (iteration : '+IntToStr(i)+')');
ProcessLoop;
end;
end;
Terminate;
end;
begin
Application:=TClientApplication.Create(Nil);
try
Application.Initialize;
Application.Run;
finally
Application.Free;
end;
end.

View File

@ -0,0 +1,65 @@
<?xml version="1.0" encoding="UTF-8"?>
<CONFIG>
<ProjectOptions>
<Version Value="9"/>
<General>
<Flags>
<MainUnitHasCreateFormStatements Value="False"/>
<MainUnitHasTitleStatement Value="False"/>
</Flags>
<SessionStorage Value="InProjectDir"/>
<MainUnit Value="0"/>
<Title Value="serverapp"/>
<UseAppBundle Value="False"/>
<ResourceType Value="res"/>
</General>
<i18n>
<EnableI18N LFM="False"/>
</i18n>
<VersionInfo>
<StringTable ProductVersion=""/>
</VersionInfo>
<BuildModes Count="1">
<Item1 Name="Default" Default="True"/>
</BuildModes>
<PublishOptions>
<Version Value="2"/>
</PublishOptions>
<RunParams>
<local>
<FormatVersion Value="1"/>
</local>
</RunParams>
<Units Count="1">
<Unit0>
<Filename Value="serverapp.pp"/>
<IsPartOfProject Value="True"/>
<UnitName Value="serverapp"/>
</Unit0>
</Units>
</ProjectOptions>
<CompilerOptions>
<Version Value="11"/>
<Target>
<Filename Value="serverapp"/>
</Target>
<Parsing>
<SyntaxOptions>
<UseAnsiStrings Value="False"/>
</SyntaxOptions>
</Parsing>
</CompilerOptions>
<Debugging>
<Exceptions Count="3">
<Item1>
<Name Value="EAbort"/>
</Item1>
<Item2>
<Name Value="ECodetoolError"/>
</Item2>
<Item3>
<Name Value="EFOpenError"/>
</Item3>
</Exceptions>
</Debugging>
</CONFIG>

View File

@ -0,0 +1,145 @@
program serverapp;
{$mode objfpc}{$H+}
{$IFDEF WINDOWS}
{$APPTYPE CONSOLE}
{$ENDIF}
uses
Classes, SysUtils, enet, uenetclass, custapp;
type
{ TServerApplication }
TServerApplication = class(TCustomApplication)
Private
myServer : TENetClass;
FIdleCount : Int64;
procedure ProcessLoop;
procedure OnConnect(const Event:ENetEvent);
procedure OnReceive(const Event:ENetEvent; var BroadcastMsg : Boolean; var BroadcastChannel : Byte);
procedure ResetIdle;
procedure StartServer(APort, ATimeout: Integer);
procedure WriteHelp;
protected
Procedure DoRun; override;
public
constructor Create(AOwner : TComponent); override;
Destructor Destroy; override;
{ public declarations }
end;
constructor TServerApplication.Create(AOwner: TComponent);
begin
Inherited;
StopOnException:=True;
end;
procedure TServerApplication.StartServer(APort,ATimeout : Integer);
begin
myServer := TENetClass.Create(APort,True);
myServer.OnReceive:=@OnReceive;
myServer.OnConnect:=@OnConnect;
myServer.OnDisconnect:=@OnConnect;
myServer.OnNone:=@OnConnect;
myServer.MessageTimeout:=ATimeOut; // ideal for application idle?
myServer.InitHost;
end;
procedure TServerApplication.WriteHelp;
begin
Writeln('Usage ',ExtractFileName(Self.ExeName),' [options]');
Writeln('Where options is one or more of');
Writeln('-h --help This message');
Writeln('-p --port=portno Port to listen on (default 30000)');
Writeln('-t --timeout=msec Timeout for listening to messages (milliseconds, default 1000)');
end;
procedure TServerApplication.DoRun;
Var
T,P : Integer;
begin
if HasOption('h','help') then
begin
WriteHelp;
Terminate;
exit;
end;
P:=StrToIntDef(GetoptionValue('p','port'),0);
T:=StrToIntDef(GetoptionValue('t','timeout'),0);
if P=0 then
P:=30000;
if t=0 then
T:=1000; // 1 second timeout,
StartServer(P,T);
FIdleCount:=0;
repeat
ProcessLoop;
if FIdleCount=0 then
Write('[idle');
Write('.');
Inc(FIdleCount);
until terminated;
end;
procedure TServerApplication.ProcessLoop;
begin
myServer.ProcessMsg;
end;
destructor TServerApplication.Destroy;
begin
myServer.Free;
end;
procedure TServerApplication.ResetIdle;
begin
if FIdleCount>0 then
Writeln(']');
FIdleCount:=0;
end;
procedure TServerApplication.OnConnect(const Event: ENetEvent);
begin
ResetIdle;
if (Event.Kind=ENet_Event_type_Connect) then
Writeln('Connect on channel : ',Event.channelID,' connected ID ,',Event.peer^.connectID,' (peer : ',Event.peer^.address.host,' port ',Event.peer^.address.port,')')
else if Event.Kind=ENet_Event_type_DisConnect then
Writeln('Disonnect on channel : ',Event.channelID,' connected ID ,',Event.peer^.connectID,' (peer : ',Event.peer^.address.host,' port ',Event.peer^.address.port,')')
else
Writeln('Unspecified connect event');
end;
procedure TServerApplication.OnReceive(const Event: ENetEvent; var BroadcastMsg: Boolean;
var BroadcastChannel: Byte);
var
msg : string;
begin
ResetIdle;
msg := PChar(Event.packet^.data);
Writeln('Received message on channel : ',Event.channelID,' connected ID ,',Event.peer^.connectID,' (peer : ',Event.peer^.address.host,' port ',Event.peer^.address.port,')');
Writeln('Message reads : "',Msg,'"');
end;
Var
Application : TServerApplication;
begin
Application:=TServerApplication.Create(Nil);
try
Application.Initialize;
Application.Run;
finally
Application.Free;
end;
end.

View File

@ -0,0 +1,57 @@
{$ifndef ALLPACKAGES}
{$mode objfpc}{$H+}
program fpmake;
uses fpmkunit;
Var
P : TPackage;
T : TTarget;
begin
With Installer do
begin
{$endif ALLPACKAGES}
P:=AddPackage('libenet');
P.ShortName:='libenet';
{$ifdef ALLPACKAGES}
P.Directory:=ADirectory;
{$endif ALLPACKAGES}
P.Version:='3.1.1';
P.SourcePath.Add('src');
P.SourcePath.Add('examples');
P.IncludePath.Add('src');
P.OSes := AllUnixOSes+AllWindowsOSes-[qnx];
T:=P.Targets.AddUnit('enettypes.pp');
T:=P.Targets.AddUnit('enetlist.pp');
T:=P.Targets.AddUnit('enetcallbacks.pp');
with T.Dependencies do
AddUnit('enettypes');
T:=P.Targets.AddUnit('enetplatform.pp');
T:=P.Targets.AddUnit('enetprotocol.pp');
T:=P.Targets.AddUnit('enettime.pp');
T:=P.Targets.AddUnit('enet.pp');
with T.Dependencies do
begin
AddUnit('enettypes');
AddUnit('enetprotocol');
AddUnit('enetlist');
AddUnit('enetcallbacks');
AddUnit('enetprotocol');
end;
T:=P.Targets.AddUnit('uenetclass.pp');
with T.Dependencies do
begin
AddUnit('enet');
AddUnit('enettime');
AddUnit('enetprotocol');
end;
P.Targets.AddExampleProgram('serverapp.pp');
P.Targets.AddExampleProgram('clientapp.pp');
{$ifndef ALLPACKAGES}
Run;
end;
end.
{$endif ALLPACKAGES}

View File

@ -0,0 +1,407 @@
{$mode objfpc}
unit enet;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enet.pp
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original file: enet.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
uses
enetplatform, enettypes, enetprotocol, enetlist, enetcallbacks;
const
ENET_VERSION_MAJOR = 1;
ENET_VERSION_MINOR = 3;
ENET_VERSION_PATCH = 12;
ENET_HOST_ANY = 0;
ENET_HOST_BROADCAST : LongWord = $FFFFFFFF;
ENET_PORT_ANY = 0;
ENET_BUFFER_MAXIMUM = 1 + 2 * ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS;
ENET_HOST_RECEIVE_BUFFER_SIZE = 256 * 1024;
ENET_HOST_SEND_BUFFER_SIZE = 256 * 1024;
ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL = 1000;
ENET_HOST_DEFAULT_MTU = 1400;
ENET_HOST_DEFAULT_MAXIMUM_PACKET_SIZE = 32 * 1024 * 1024;
ENET_HOST_DEFAULT_MAXIMUM_WAITING_DATA = 32 * 1024 * 1024;
ENET_PEER_DEFAULT_ROUND_TRIP_TIME = 500;
ENET_PEER_DEFAULT_PACKET_THROTTLE = 32;
ENET_PEER_PACKET_THROTTLE_SCALE = 32;
ENET_PEER_PACKET_THROTTLE_COUNTER = 7;
ENET_PEER_PACKET_THROTTLE_ACCELERATION = 2;
ENET_PEER_PACKET_THROTTLE_DECELERATION = 2;
ENET_PEER_PACKET_THROTTLE_INTERVAL = 5000;
ENET_PEER_PACKET_LOSS_SCALE = 1 shl 16;
ENET_PEER_PACKET_LOSS_INTERVAL = 10000;
ENET_PEER_WINDOW_SIZE_SCALE = 64 * 1024;
ENET_PEER_TIMEOUT_LIMIT = 32;
ENET_PEER_TIMEOUT_MINIMUM = 5000;
ENET_PEER_TIMEOUT_MAXIMUM = 30000;
ENET_PEER_PING_INTERVAL = 500;
ENET_PEER_UNSEQUENCED_WINDOWS = 64;
ENET_PEER_UNSEQUENCED_WINDOW_SIZE = 1024;
ENET_PEER_FREE_UNSEQUENCED_WINDOWS = 32;
ENET_PEER_RELIABLE_WINDOWS = 16;
ENET_PEER_RELIABLE_WINDOW_SIZE = $1000;
ENET_PEER_FREE_RELIABLE_WINDOWS = 8;
type
//enums
ENetSocketType = ( ENET_SOCKET_TYPE_STREAM = 1,
ENET_SOCKET_TYPE_DATAGRAM = 2 );
ENetSocketWait = ( ENET_SOCKET_WAIT_NONE = 0,
ENET_SOCKET_WAIT_SEND = 1,
ENET_SOCKET_WAIT_RECEIVE = 2,
ENET_SOCKET_WAIT_INTERRUPT = 4 );
ENetSocketOption = ( ENET_SOCKOPT_NONBLOCK = 1,
ENET_SOCKOPT_BROADCAST = 2,
ENET_SOCKOPT_RCVBUF = 3,
ENET_SOCKOPT_SNDBUF = 4,
ENET_SOCKOPT_REUSEADDR = 5,
ENET_SOCKOPT_RCVTIMEO = 6,
ENET_SOCKOPT_SNDTIMEO = 7,
ENET_SOCKOPT_ERROR = 8,
ENET_SOCKOPT_NODELAY = 9 );
ENetSocketShutdown = ( ENET_SOCKET_SHUTDOWN_READ,
ENET_SOCKET_SHUTDOWN_WRITE,
ENET_SOCKET_SHUTDOWN_READ_WRITE );
Const
ENET_PACKET_FLAG_RELIABLE = 1;
ENET_PACKET_FLAG_UNSEQUENCED = 2;
ENET_PACKET_FLAG_NO_ALLOCATE = 4;
ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT = 8;
ENET_PACKET_FLAG_SENT = 256;
Type
ENetPeerState = ( ENET_PEER_STATE_DISCONNECTED,
ENET_PEER_STATE_CONNECTING,
ENET_PEER_STATE_ACKNOWLEDGING_CONNECT,
ENET_PEER_STATE_CONNECTION_PENDING,
ENET_PEER_STATE_CONNECTION_SUCCEEDED,
ENET_PEER_STATE_CONNECTED,
ENET_PEER_STATE_DISCONNECT_LATER,
ENET_PEER_STATE_DISCONNECTING,
ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT,
ENET_PEER_STATE_ZOMBIE );
ENetEventType = ( ENET_EVENT_TYPE_NONE,
ENET_EVENT_TYPE_CONNECT,
ENET_EVENT_TYPE_DISCONNECT,
ENET_EVENT_TYPE_RECEIVE );
//definitions
ENetVersion = enet_uint32;
//structs pointers
pENetAddress = ^ENetAddress;
pENetPacket = ^ENetPacket;
pENetAcknowledgement = ^ENetAcknowledgement;
pENetOutgoingCommand = ^ENetOutgoingCommand;
pENetIncomingCommand = ^ENetIncomingCommand;
pENetChannel = ^ENetChannel;
pENetPeer = ^ENetPeer;
pENetCompressor = ^ENetCompressor;
pENetHost = ^ENetHost;
pENetEvent = ^ENetEvent;
//callbacks
ENetPacketFreeCallback = procedure( packet: pENetPacket ); cdecl;
ENetChecksumCallback = function( const buffers: pENetBuffer; bufferCount: enet_size_t ): enet_uint32; cdecl;
ENetInterceptCallback = function( host: pENetHost; event: pENetEvent ): enet_int; cdecl;
{$PACKRECORDS C}
//structs
ENetAddress = record
host : enet_uint32;
port : enet_uint16;
end;
ENetPacket = record
referenceCount : enet_size_t;
flags : enet_uint32;
data : penet_uint8;
dataLength : enet_size_t;
freeCallback : ENetPacketFreeCallback;
userData : Pointer;
end;
ENetAcknowledgement = record
acknowledgementList : ENetListNode;
sentTime : enet_uint32;
command : TENetProtocol;
end;
ENetOutgoingCommand = record
outgoingCommandList : ENetListNode;
reliableSequenceNumber : enet_uint16;
unreliableSequenceNumber : enet_uint16;
sentTime : enet_uint32;
roundTripTimeout : enet_uint32;
roundTripTimeoutLimit : enet_uint32;
fragmentOffset : enet_uint32;
fragmentLength : enet_uint16;
sendAttempts : enet_uint16;
command : TENetProtocol;
packet : pENetPacket;
end;
ENetIncomingCommand = record
incomingCommandList : ENetListNode;
reliableSequenceNumber : enet_uint16;
unreliableSequenceNumber : enet_uint16;
command : TENetProtocol;
fragmentCount : enet_uint32;
fragmentsRemaining : enet_uint32;
fragments : penet_uint32;
packet : pENetPacket;
end;
ENetChannel = record
outgoingReliableSequenceNumber : enet_uint16;
outgoingUnreliableSequenceNumber : enet_uint16;
usedReliableWindows : enet_uint16;
reliableWindows : array[ 0..ENET_PEER_RELIABLE_WINDOWS-1 ] of enet_uint16;
incomingReliableSequenceNumber : enet_uint16;
incomingUnreliableSequenceNumber : enet_uint16;
incomingReliableCommands : TENetList;
incomingUnreliableCommands : TENetList;
end;
ENetPeer = record
dispatchList : ENetListNode;
host : pENetHost;
outgoingPeerID : enet_uint16;
incomingPeerID : enet_uint16;
connectID : enet_uint32;
outgoingSessionID : enet_uint8;
incomingSessionID : enet_uint8;
address : ENetAddress;
data : Pointer;
state : ENetPeerState;
channels : pENetChannel;
channelCount : enet_size_t;
incomingBandwidth : enet_uint32;
outgoingBandwidth : enet_uint32;
incomingBandwidthThrottleEpoch : enet_uint32;
outgoingBandwidthThrottleEpoch : enet_uint32;
incomingDataTotal : enet_uint32;
outgoingDataTotal : enet_uint32;
lastSendTime : enet_uint32;
lastReceiveTime : enet_uint32;
nextTimeout : enet_uint32;
earliestTimeout : enet_uint32;
packetLossEpoch : enet_uint32;
packetsSent : enet_uint32;
packetsLost : enet_uint32;
packetLoss : enet_uint32;
packetLossVariance : enet_uint32;
packetThrottle : enet_uint32;
packetThrottleLimit : enet_uint32;
packetThrottleCounter : enet_uint32;
packetThrottleEpoch : enet_uint32;
packetThrottleAcceleration : enet_uint32;
packetThrottleDeceleration : enet_uint32;
packetThrottleInterval : enet_uint32;
pingInterval : enet_uint32;
timeoutLimit : enet_uint32;
timeoutMinimum : enet_uint32;
timeoutMaximum : enet_uint32;
lastRoundTripTime : enet_uint32;
lowestRoundTripTime : enet_uint32;
lastRoundTripTimeVariance : enet_uint32;
highestRoundTripTimeVariance : enet_uint32;
roundTripTime : enet_uint32;
roundTripTimeVariance : enet_uint32;
mtu : enet_uint32;
windowSize : enet_uint32;
reliableDataInTransit : enet_uint32;
outgoingReliableSequenceNumber : enet_uint16;
acknowledgements : TENetList;
sentReliableCommands : TENetList;
sentUnreliableCommands : TENetList;
outgoingReliableCommands : TENetList;
outgoingUnreliableCommands : TENetList;
dispatchedCommands : TENetList;
needsDispatch : enet_int;
incomingUnsequencedGroup : enet_uint16;
outgoingUnsequencedGroup : enet_uint16;
unsequencedWindow : array[ 0..(ENET_PEER_UNSEQUENCED_WINDOW_SIZE div 32)-1 ] of enet_uint32;
eventData : enet_uint32;
totalWaitingData : enet_size_t;
end;
ENetCompressor = record
context : Pointer;
compress : function( context: Pointer; const inBuffers: pENetBuffer; inBufferCount, inLimit: enet_size_t; outData: penet_uint8; outLimit: enet_size_t ): enet_size_t; cdecl;
decompress : function( context: Pointer; const inData: penet_uint8; inLimit: enet_size_t; outData: penet_uint8; outLimit: enet_size_t ): enet_size_t; cdecl;
destroy : procedure( context: Pointer ); cdecl;
end;
ENetHost = record
socket : ENetSocket;
address : ENetAddress;
incomingBandwidth : enet_uint32;
outgoingBandwidth : enet_uint32;
bandwidthThrottleEpoch : enet_uint32;
mtu : enet_uint32;
randomSeed : enet_uint32;
recalculateBandwidthLimits : enet_int;
peers : pENetPeer;
peerCount : enet_size_t;
channelLimit : enet_size_t;
serviceTime : enet_uint32;
dispatchQueue : TENetList;
continueSending : enet_int;
packetSize : enet_size_t;
headerFlags : enet_uint16;
commands : array[ 0..ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS-1 ] of TENetProtocol;
commandCount : enet_size_t;
buffers : array[ 0..ENET_BUFFER_MAXIMUM-1 ] of ENetBuffer;
bufferCount : enet_size_t;
checksum : ENetChecksumCallback;
compressor : ENetCompressor;
packetData : array[ 0..1, 0..ENET_PROTOCOL_MAXIMUM_MTU-1 ] of enet_uint8;
receivedAddress : ENetAddress;
receivedData : penet_uint8;
receivedDataLength : enet_size_t;
totalSentData : enet_uint32;
totalSentPackets : enet_uint32;
totalReceivedData : enet_uint32;
totalReceivedPackets : enet_uint32;
intercept : ENetInterceptCallback;
connectedPeers : enet_size_t;
bandwidthLimitedPeers : enet_size_t;
duplicatePeers : enet_size_t;
maximumPacketSize : enet_size_t;
maximumWaitingData : enet_size_t;
end;
ENetEvent = record
kind : ENetEventType; //originally "type", which conflicts
peer : pENetPeer;
channelID : enet_uint8;
data : enet_uint32;
packet : pENetPacket;
end;
{$PACKRECORDS DEFAULT}
//inline macros
function ENET_VERSION_CREATE( const major, minor, patch: LongInt ): ENetVersion; inline;
function ENET_VERSION_GET_MAJOR( const version: ENetVersion ): LongInt; inline;
function ENET_VERSION_GET_MINOR( const version: ENetVersion ): LongInt; inline;
function ENET_VERSION_GET_PATCH( const version: ENetVersion ): LongInt; inline;
function ENET_VERSION(): ENetVersion; inline;
//external
{$MACRO ON}
{$DEFINE libraryENet := cdecl; external 'enet'}
function enet_initialize(): enet_int; libraryENet;
function enet_initialize_with_callbacks( version: ENetVersion; const inits: pENetCallbacks ): enet_int; libraryENet;
procedure enet_deinitialize(); libraryENet;
function enet_linked_version(): ENetVersion; libraryENet;
function enet_time_get(): enet_uint32; libraryENet;
procedure enet_time_set( newTimeBase: enet_uint32 ); libraryENet;
function enet_socket_create( kind: ENetSocketType ): ENetSocket; libraryENet;
function enet_socket_bind( socket: ENetSocket; const address: pENetAddress ): enet_int; libraryENet;
function enet_socket_get_address( socket: ENetSocket; address: pENetAddress ): enet_int; libraryENet;
function enet_socket_listen( socket: ENetSocket; backlog: enet_int ): enet_int; libraryENet;
function enet_socket_accept( socket: ENetSocket; address: pENetAddress ): ENetSocket; libraryENet;
function enet_socket_connect( socket: ENetSocket; const address: pENetAddress ): enet_int; libraryENet;
function enet_socket_send( socket: ENetSocket; const address: pENetAddress; const buffers: pENetBuffer; bufferCount: enet_size_t ): enet_int; libraryENet;
function enet_socket_receive( socket: ENetSocket; address: pENetAddress; buffers: pENetBuffer; bufferCount: enet_size_t ): enet_int; libraryENet;
function enet_socket_wait( socket: ENetSocket; condition: penet_uint32; timeout: enet_uint32 ): enet_int; libraryENet;
function enet_socket_set_option( socket: ENetSocket; option: ENetSocketOption; value: enet_int ): enet_int; libraryENet;
function enet_socket_get_option( socket: ENetSocket; option: ENetSocketOption; value: penet_int ): enet_int; libraryENet;
function enet_socket_shutdown( socket: ENetSocket; how: ENetSocketShutdown ): enet_int; libraryENet;
procedure enet_socket_destroy( socket: ENetSocket ); libraryENet;
function enet_socketset_select( maxSocket: ENetSocket; readSet: pENetSocketSet; writeSet: pENetSocketSet; timeout: enet_uint32 ): enet_int; libraryENet;
function enet_address_set_host( address: pENetAddress; const hostName: PChar ): enet_int; libraryENet;
function enet_address_get_host_ip( const address: pENetAddress; hostName: PChar; nameLength: enet_size_t ): enet_int; libraryENet;
function enet_address_get_host( const address: pENetAddress; hostName: PChar; nameLength: enet_size_t ): enet_int; libraryENet;
function enet_packet_create( const data: Pointer; dataLength: enet_size_t; flags: enet_uint32 ): pENetPacket; libraryENet;
procedure enet_packet_destroy( packet: pENetPacket ); libraryENet;
function enet_packet_resize( packet: pENetPacket; dataLength: enet_size_t ): enet_int; libraryENet;
function enet_crc32( const buffers: pENetBuffer; bufferCount: enet_size_t ): enet_uint32; libraryENet;
function enet_host_create( const address: pENetAddress; peerCount, channelLimit: enet_size_t; incomingBandwidth, outgoingBandwidth: enet_uint32 ): pENetHost; libraryENet;
procedure enet_host_destroy( host: pENetHost ); libraryENet;
function enet_host_connect( host: pENetHost; const address: pENetAddress; channelCount: enet_size_t; data: enet_uint32 ): pENetPeer; libraryENet;
function enet_host_check_events( host: pENetHost; event: pENetEvent ): enet_int; libraryENet;
function enet_host_service( host: pENetHost; event: pENetEvent; timeout: enet_uint32 ): enet_int; libraryENet;
procedure enet_host_flush( host: pENetHost ); libraryENet;
procedure enet_host_widecast( host: pENetHost; channelID: enet_uint8; packet: pENetPacket ); libraryENet name 'enet_host_broadcast'; //renamed due to names conflict
procedure enet_host_compress( host: pENetHost; const compressor: pENetCompressor ); libraryENet;
function enet_host_compress_with_range_coder( host: pENetHost ): enet_int; libraryENet;
procedure enet_host_channel_limit( host: pENetHost; channelLimit: enet_size_t ); libraryENet;
procedure enet_host_bandwidth_limit( host: pENetHost; incomingBandwidth, outgoingBandwidth: enet_uint32 ); libraryENet;
function enet_peer_send( peer: pENetPeer; channelID: enet_uint8; packet: pENetPacket ): enet_int; libraryENet;
function enet_peer_receive( peer: pENetPeer; channelID: penet_uint8 ): pENetPacket; libraryENet;
procedure enet_peer_ping( peer: pENetPeer ); libraryENet;
procedure enet_peer_ping_frequency( peer: pENetPeer; pingInterval: enet_uint32 ); libraryENet name 'enet_peer_ping_interval'; //renamed due to names conflict
procedure enet_peer_timeout( peer: pENetPeer; timeoutLimit, timeoutMinimum, timeoutMaximum: enet_uint32 ); libraryENet;
procedure enet_peer_reset( peer: pENetPeer ); libraryENet;
procedure enet_peer_disconnect( peer: pENetPeer; data: enet_uint32 ); libraryENet;
procedure enet_peer_disconnect_now( peer: pENetPeer; data: enet_uint32 ); libraryENet;
procedure enet_peer_disconnect_later( peer: pENetPeer; data: enet_uint32 ); libraryENet;
procedure enet_peer_throttle_configure( peer: pENetPeer; interval, acceleration, deceleration: enet_uint32 ); libraryENet;
function enet_range_coder_create(): Pointer; libraryENet;
procedure enet_range_coder_destroy( context: Pointer ); libraryENet;
function enet_range_coder_compress( context: Pointer; const inBuffers: pENetBuffer; inBufferCount, inLiit: enet_size_t; outData: penet_uint8; outLimit: enet_size_t ): enet_size_t; libraryENet;
function enet_range_coder_decompress( context: Pointer; const inData: penet_uint8; inLimit: enet_size_t; outData: penet_uint8; outLimit: enet_size_t ): enet_size_t; libraryENet;
implementation
function ENET_VERSION_CREATE( const major, minor, patch: LongInt ): ENetVersion; inline;
begin Result := (major shl 16) or (minor shl 8) or patch;
end;
function ENET_VERSION_GET_MAJOR( const version: ENetVersion ): LongInt; inline;
begin Result := (version shr 16) and $FF;
end;
function ENET_VERSION_GET_MINOR( const version: ENetVersion ): LongInt; inline;
begin Result := (version shr 8) and $FF;
end;
function ENET_VERSION_GET_PATCH( const version: ENetVersion ): LongInt; inline;
begin Result := version and $FF;
end;
function ENET_VERSION(): ENetVersion; inline;
begin Result := ENET_VERSION_CREATE( ENET_VERSION_MAJOR, ENET_VERSION_MINOR, ENET_VERSION_PATCH );
end;
end.

View File

@ -0,0 +1,54 @@
{$mode objfpc}{$H+}
unit enetcallbacks;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enetcallbacks.pp
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original file: callbacks.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
uses enettypes; //only for size_t
type
{$PACKRECORDS C}
pENetCallbacks = ^TENetCallbacks;
TENetCallbacks = record
malloc : function( size: enet_size_t ): Pointer; cdecl;
free : procedure( memory: Pointer ); cdecl;
no_memory : procedure(); cdecl;
end;
{$PACKRECORDS DEFAULT}
implementation
end.

View File

@ -0,0 +1,95 @@
{$mode objfpc}{$H+}
unit enetlist;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enetlist.pp
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original file: list.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
type
{$PACKRECORDS C}
pENetListNode = ^ENetListNode;
ENetListNode = record
next : pENetListNode;
previous : pENetListNode;
end;
ENetListIterator = pENetListNode;
pENetList = ^TENetList;
TENetList = record
sentinel : ENetListNode;
end;
{$PACKRECORDS DEFAULT}
//inline macros
function enet_list_begin( list: pENetList ): ENetListIterator; inline;
function enet_list_end( list: pENetList ): ENetListIterator; inline;
function enet_list_empty( list: pENetList ): Boolean; inline;
function enet_list_next( iterator: ENetListIterator ): ENetListIterator; inline;
function enet_list_previous( iterator: ENetListIterator ): ENetListIterator; inline;
function enet_list_front( list: pENetList ): Pointer; inline;
function enet_list_back( list: pENetList ): Pointer; inline;
implementation
function enet_list_begin( list: pENetList ): ENetListIterator; inline;
begin Result := list^.sentinel.next;
end;
function enet_list_end( list: pENetList ): ENetListIterator; inline;
begin Result := @( list^.sentinel );
end;
function enet_list_empty( list: pENetList ): Boolean; inline;
begin Result := enet_list_begin(list) = enet_list_end(list);
end;
function enet_list_next( iterator: ENetListIterator ): ENetListIterator; inline;
begin Result := iterator^.next;
end;
function enet_list_previous( iterator: ENetListIterator ): ENetListIterator; inline;
begin Result := iterator^.previous;
end;
function enet_list_front( list: pENetList ): Pointer; inline;
begin Result := Pointer( list^.sentinel.next );
end;
function enet_list_back( list: pENetList ): Pointer; inline;
begin Result := Pointer( list^.sentinel.previous );
end;
end.

View File

@ -0,0 +1,108 @@
{$mode objfpc}{$H+}
unit enetplatform;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enetplatform
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original files: win32.h & unix.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
uses enettypes, // used only for size_t
{$IFDEF MSWINDOWS} WinSock2 {$ELSE} BaseUnix, Sockets {$ENDIF};
const
ENET_SOCKET_NULL = {$IFDEF MSWINDOWS} INVALID_SOCKET; {$ELSE} -1; {$ENDIF}
// ENET_BUFFER_MAXIMUM = MSG_MAXIOVLEN; //is it forgotten in win32.h ?
type
ENetSocket = {$IFDEF MSWINDOWS} TSocket {$ELSE} enet_int {$ENDIF};
ENetSocketSet = TFDSet;
pENetSocketSet = ^ENetSocketSet;
{$PACKRECORDS C}
pENetBuffer = ^ENetBuffer;
ENetBuffer = record
{$IFDEF MSWINDOWS}
dataLength : enet_size_t;
data : Pointer;
{$ELSE}
data : Pointer;
dataLength : enet_size_t;
{$ENDIF}
end;
{$PACKRECORDS DEFAULT}
//inline macros
function ENET_HOST_TO_NET_16( const value: Word ): Word; inline;
function ENET_HOST_TO_NET_32( const value: LongWord ): LongWord; inline;
function ENET_NET_TO_HOST_16( const value: Word ): Word; inline;
function ENET_NET_TO_HOST_32( const value: LongWord ): LongWord; inline;
procedure ENET_SOCKETSET_EMPTY( var sockset: ENetSocketSet ); inline;
procedure ENET_SOCKETSET_ADD( var sockset: ENetSocketSet; socket: ENetSocket ); inline;
procedure ENET_SOCKETSET_REMOVE( var sockset: ENetSocketSet; socket: ENetSocket ); inline;
function ENET_SOCKETSET_CHECK( var sockset: ENetSocketSet; socket: ENetSocket ): Boolean; inline;
implementation
function ENET_HOST_TO_NET_16( const value: Word ): Word; inline;
begin Result := htons(value);
end;
function ENET_HOST_TO_NET_32( const value: LongWord ): LongWord; inline;
begin Result := htonl(value);
end;
function ENET_NET_TO_HOST_16( const value: Word ): Word; inline;
begin Result := ntohs(value);
end;
function ENET_NET_TO_HOST_32( const value: LongWord ): LongWord; inline;
begin Result := ntohl(value);
end;
procedure ENET_SOCKETSET_EMPTY( var sockset: ENetSocketSet ); inline;
begin {$IFNDEF MSWINDOWS}fpFD_ZERO{$ELSE}FD_ZERO{$ENDIF}( sockset );
end;
procedure ENET_SOCKETSET_ADD( var sockset: ENetSocketSet; socket: ENetSocket ); inline;
begin {$IFNDEF MSWINDOWS}fpFD_SET{$ELSE}FD_SET{$ENDIF}( socket, sockset );
end;
procedure ENET_SOCKETSET_REMOVE( var sockset: ENetSocketSet; socket: ENetSocket ); inline;
begin {$IFNDEF MSWINDOWS}fpFD_CLR{$ELSE}FD_CLR{$ENDIF}( socket, sockset );
end;
function ENET_SOCKETSET_CHECK( var sockset: ENetSocketSet; socket: ENetSocket ): Boolean; inline;
begin Result := {$IFNDEF MSWINDOWS} fpFD_ISSET( socket, sockset ) <> 0
{$ELSE} FD_ISSET( socket, sockset ) {$ENDIF};
end;
end.

View File

@ -0,0 +1,214 @@
{$mode objfpc}
unit enetprotocol;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enetprotocol.pp
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original file: protocol.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
uses enettypes;
const
ENET_PROTOCOL_MINIMUM_MTU = 576;
ENET_PROTOCOL_MAXIMUM_MTU = 4096;
ENET_PROTOCOL_MAXIMUM_PACKET_COMMANDS = 32;
ENET_PROTOCOL_MINIMUM_WINDOW_SIZE = 4096;
ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE = 65536;
ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT = 1;
ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT = 255;
ENET_PROTOCOL_MAXIMUM_PEER_ID = $FFF;
ENET_PROTOCOL_MAXIMUM_FRAGMENT_COUNT = 1024 * 1024;
// ENetProtocolFlag
ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE = 1 shl 7;
ENET_PROTOCOL_COMMAND_FLAG_UNSEQUENCED = 1 shl 6;
ENET_PROTOCOL_HEADER_FLAG_COMPRESSED = 1 shl 14;
ENET_PROTOCOL_HEADER_FLAG_SENT_TIME = 1 shl 15;
ENET_PROTOCOL_HEADER_FLAG_MASK = ENET_PROTOCOL_HEADER_FLAG_COMPRESSED or
ENET_PROTOCOL_HEADER_FLAG_SENT_TIME;
ENET_PROTOCOL_HEADER_SESSION_MASK = 3 shl 12;
ENET_PROTOCOL_HEADER_SESSION_SHIFT = 12;
type
ENetProtocolCommand = ( ENET_PROTOCOL_COMMAND_NONE,
ENET_PROTOCOL_COMMAND_ACKNOWLEDGE,
ENET_PROTOCOL_COMMAND_CONNECT,
ENET_PROTOCOL_COMMAND_VERIFY_CONNECT,
ENET_PROTOCOL_COMMAND_DISCONNECT,
ENET_PROTOCOL_COMMAND_PING,
ENET_PROTOCOL_COMMAND_SEND_RELIABLE,
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE,
ENET_PROTOCOL_COMMAND_SEND_FRAGMENT,
ENET_PROTOCOL_COMMAND_SEND_UNSEQUENCED,
ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT,
ENET_PROTOCOL_COMMAND_THROTTLE_CONFIGURE,
ENET_PROTOCOL_COMMAND_SEND_UNRELIABLE_FRAGMENT,
ENET_PROTOCOL_COMMAND_COUNT,
ENET_PROTOCOL_COMMAND_MASK = $0F );
ENetProtocolFlag = Integer; //alias for FPC-uncompatible enum, placed in const
{$PACKRECORDS 1}
pENetProtocolHeader = ^ENetProtocolHeader;
ENetProtocolHeader = record
peerID : enet_uint16;
sentTime : enet_uint16;
end;
pENetProtocolCommandHeader = ^ENetProtocolCommandHeader;
ENetProtocolCommandHeader = record
command : enet_uint8;
channelID : enet_uint8;
reliableSequenceNumber : enet_uint16;
end;
pENetProtocolAcknowledge = ^ENetProtocolAcknowledge;
ENetProtocolAcknowledge = record
header : ENetProtocolCommandHeader;
receivedReliableSequenceNumber : enet_uint16;
receivedSentTime : enet_uint16;
end;
pENetProtocolConnect = ^ENetProtocolConnect;
ENetProtocolConnect = record
header : ENetProtocolCommandHeader;
outgoingPeerID : enet_uint16;
incomingSessionID : enet_uint8;
outgoingSessionID : enet_uint8;
mtu : enet_uint32;
windowSize : enet_uint32;
channelCount : enet_uint32;
incomingBandwidth : enet_uint32;
outgoingBandwidth : enet_uint32;
packetThrottleInterval : enet_uint32;
packetThrottleAcceleration : enet_uint32;
packetThrottleDeceleration : enet_uint32;
connectID : enet_uint32;
data : enet_uint32;
end;
pENetProtocolVerifyConnect = ^ENetProtocolVerifyConnect;
ENetProtocolVerifyConnect = record
header : ENetProtocolCommandHeader;
outgoingPeerID : enet_uint16;
incomingSessionID : enet_uint8;
outgoingSessionID : enet_uint8;
mtu : enet_uint32;
windowSize : enet_uint32;
channelCount : enet_uint32;
incomingBandwidth : enet_uint32;
outgoingBandwidth : enet_uint32;
packetThrottleInterval : enet_uint32;
packetThrottleAcceleration : enet_uint32;
packetThrottleDeceleration : enet_uint32;
connectID : enet_uint32;
end;
pENetProtocolBandwidthLimit = ^ENetProtocolBandwidthLimit;
ENetProtocolBandwidthLimit = record
header : ENetProtocolCommandHeader;
incomingBandwidth : enet_uint32;
outgoingBandwidth : enet_uint32;
end;
pENetProtocolThrottleConfigure = ^ENetProtocolThrottleConfigure;
ENetProtocolThrottleConfigure = record
header : ENetProtocolCommandHeader;
packetThrottleInterval : enet_uint32;
packetThrottleAcceleration : enet_uint32;
packetThrottleDeceleration : enet_uint32;
end;
pENetProtocolDisconnect = ^ENetProtocolDisconnect;
ENetProtocolDisconnect = record
header : ENetProtocolCommandHeader;
data : enet_uint32;
end;
pENetProtocolPing = ^ENetProtocolPing;
ENetProtocolPing = record
header : ENetProtocolCommandHeader;
end;
pENetProtocolSendReliable = ^ENetProtocolSendReliable;
ENetProtocolSendReliable = record
header : ENetProtocolCommandHeader;
dataLength : enet_uint16;
end;
pENetProtocolSendUnreliable = ^ENetProtocolSendUnreliable;
ENetProtocolSendUnreliable = record
header : ENetProtocolCommandHeader;
unreliableSequenceNumber : enet_uint16;
dataLength : enet_uint16;
end;
pENetProtocolSendUnsequenced = ^ENetProtocolSendUnsequenced;
ENetProtocolSendUnsequenced = record
header : ENetProtocolCommandHeader;
unsequencedGroup : enet_uint16;
dataLength : enet_uint16;
end;
pENetProtocolSendFragment = ^ENetProtocolSendFragment;
ENetProtocolSendFragment = record
header : ENetProtocolCommandHeader;
startSequenceNumber : enet_uint16;
dataLength : enet_uint16;
fragmentCount : enet_uint32;
fragmentNumber : enet_uint32;
totalLength : enet_uint32;
fragmentOffset : enet_uint32;
end;
pENetProtocol = ^TENetProtocol;
TENetProtocol = record //union
case Byte of
0 : (header : ENetProtocolCommandHeader);
1 : (acknowledge : ENetProtocolAcknowledge);
2 : (connect : ENetProtocolConnect);
3 : (verifyConnect : ENetProtocolVerifyConnect);
4 : (disconnect : ENetProtocolDisconnect);
5 : (ping : ENetProtocolPing);
6 : (sendReliable : ENetProtocolSendReliable);
7 : (sendUnreliable : ENetProtocolSendUnreliable);
8 : (sendUnsequenced : ENetProtocolSendUnsequenced);
9 : (sendFragment : ENetProtocolSendFragment);
10: (bandwidthLimit : ENetProtocolBandwidthLimit);
11: (throttleConfigure : ENetProtocolThrottleConfigure);
end;
{$PACKRECORDS DEFAULT}
implementation
end.

View File

@ -0,0 +1,69 @@
{$mode objfpc}
unit enettime;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enettime.pp
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original file: time.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
const
ENET_TIME_OVERFLOW = 86400000;
//inline macros
function ENET_TIME_LESS( const a, b: LongInt ): Boolean; inline;
function ENET_TIME_GREATER( const a, b: LongInt ): Boolean; inline;
function ENET_TIME_LESS_EQUAL( const a, b: LongInt ): Boolean; inline;
function ENET_TIME_GREATER_EQUAL( const a, b: LongInt ): Boolean; inline;
function ENET_TIME_DIFFERENCE( const a, b: LongInt ): LongInt; inline;
implementation
function ENET_TIME_LESS( const a, b: LongInt ): Boolean; inline;
begin Result := a - b >= ENET_TIME_OVERFLOW;
end;
function ENET_TIME_GREATER( const a, b: LongInt ): Boolean; inline;
begin Result := b - a >= ENET_TIME_OVERFLOW;
end;
function ENET_TIME_LESS_EQUAL( const a, b: LongInt ): Boolean; inline;
begin Result := not ENET_TIME_GREATER( a, b );
end;
function ENET_TIME_GREATER_EQUAL( const a, b: LongInt ): Boolean; inline;
begin Result := not ENET_TIME_LESS( a, b );
end;
function ENET_TIME_DIFFERENCE( const a, b: LongInt ): LongInt; inline;
begin if a - b >= ENET_TIME_OVERFLOW then Result := b - a else Result := a - b;
end;
end.

View File

@ -0,0 +1,55 @@
{$mode objfpc}
unit enettypes;
{
ENet - Reliable UDP networking library
FreePascal DLL header: enettypes.pp
Copyright (c) 2015 Dmitry D. Chernov aka Black Doomer
Original file: types.h
Copyright (c) 2002-2014 Lee Salzman
Version 1 for 1.3.12: 25.02.2015
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
}
interface
type
enet_size_t = SizeUInt; //alias for C size_t
penet_size_t = ^enet_size_t;
enet_int = LongInt; //alias for C int
penet_int = ^enet_int;
enet_uint8 = Byte;
penet_uint8 = ^enet_uint8;
enet_uint16 = Word;
penet_uint16 = ^enet_uint16;
enet_uint32 = LongWord;
penet_uint32 = ^enet_uint32;
implementation
end.

View File

@ -0,0 +1,339 @@
unit uenetclass;
{ ENet UDP Class for FreePascal
Copyright (c) 2013 Do-wan Kim
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
- Add SendMsgEventPeer
}
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, enet, enettime, enetprotocol;
type
TENet_Event_Type = (ENetEventNone, ENetEventConnect, ENetEventDisConnect, ENetEventReceive);
TENetPacketFlag = (ENetPacketReliable, ENetPacketUnsequenced,
ENetPacketNoAllocate, ENetPacketUnReliableFragment);
TENetPacketFlags = set of TENetPacketFlag;
TENetEventProc = procedure (const Event:ENetEvent) of object;
TENetEventRecv = procedure (const Event:ENetEvent; var BroadcastMsg : Boolean; var BroadcastChannel : Byte) of object;
{ TENetClass }
TENetClass = class
private
FInit : Boolean;
FHostname : string;
FAddress : ENetAddress;
FIsServer : Boolean;
FMaxPeer : Cardinal;
FMaxChannels : Byte;
FBandwidthIncoming, FBandwidthOutgoing : Cardinal;
FHost : pENetHost;
FEvent : ENetEvent;
FPeer : pENetPeer;
FClientData : Cardinal;
FConnectTimeout : Cardinal;
FMessageTimeout : Cardinal;
FEventNone : TENetEventProc;
FEventConnect : TENetEventProc;
FEventDisConnect : TENetEventProc;
FEventReceive : TENetEventRecv;
protected
public
constructor Create(Port : word; bServer : Boolean);
destructor Destroy; override;
function InitHost:Boolean;
procedure DeInitHost;
function Connect(const Host: string; Port: Word): Boolean;
function DisConnect(bNow: Boolean): Boolean;
function SendMsg(Channel: Byte; Data: Pointer; Length: Integer; flag: TENetPacketFlags;
WaitResponse: Boolean = False): Boolean;
function SendMsgEventPeer(Data: Pointer; Length: Integer;
flag: TENetPacketFlags; WaitResponse: Boolean=False): Boolean;
procedure FlushMsg;
function BroadcastMsg(Channel: Byte; Data: Pointer; Length: Integer; flag: TENetPacketFlags; WaitResponse : Boolean = False):Boolean;
function ProcessMsg:Boolean; virtual;
procedure Ping;
property Port : Word read FAddress.port write FAddress.port;
property MaxClient : Cardinal read FMaxPeer write FMaxPeer;
property MaxChannels : Byte read FMaxChannels write FMaxChannels;
property BandwidthIncoming : Cardinal read FBandwidthIncoming write FBandwidthIncoming;
property BandwidthOutgoing : Cardinal read FBandwidthOutgoing write FBandwidthOutgoing;
property ClientData : Cardinal read FClientData;
property ConnectTimeout : Cardinal read FConnectTimeout write FConnectTimeout;
property MessageTimeout : Cardinal read FMessageTimeout write FMessageTimeout;
property OnNone : TENetEventProc read FEventNone write FEventNone;
property OnConnect : TENetEventProc read FEventConnect write FEventConnect;
property OnDisconnect : TENetEventProc read FEventDisConnect write FEventDisConnect;
property OnReceive : TENetEventRecv read FEventReceive write FEventReceive;
end;
implementation
function GetPacketFlag(flag:TENetPacketFlags):Integer;
begin
Result:=0;
if ENetPacketReliable in flag then
Inc(Result,Ord(ENET_PACKET_FLAG_RELIABLE));
if ENetPacketUnsequenced in flag then
Inc(Result,Ord(ENET_PACKET_FLAG_UNSEQUENCED));
if ENetPacketNoAllocate in flag then
Inc(Result,Ord(ENET_PACKET_FLAG_NO_ALLOCATE));
if ENetPacketUnReliableFragment in flag then
Inc(Result,Ord(ENET_PACKET_FLAG_UNRELIABLE_FRAGMENT));
end;
{ TENetClass }
constructor TENetClass.Create(Port: word; bServer: Boolean);
begin
FAddress.port:=Port;
FMaxPeer:=100;
FMaxChannels:=255;
FBandwidthIncoming:=0;
FBandwidthOutgoing:=0;
FIsServer:=False;
FConnectTimeout:=5000;
FMessageTimeout:=100;
FHost:=nil;
FPeer:=nil;
FEventNone:=nil;
FEventConnect:=nil;
FEventDisConnect:=nil;
FEventReceive:=nil;
FIsServer:=bServer;
FInit := enet_initialize = 0;
end;
destructor TENetClass.Destroy;
begin
DisConnect(True);
if FInit then
enet_deinitialize;
inherited Destroy;
end;
function TENetClass.InitHost: Boolean;
begin
DeInitHost;
if FInit then
if FIsServer then begin
// for server
FAddress.host:=ENET_HOST_ANY;
FHost:=enet_host_create(@FAddress,
FMaxPeer,
FMaxChannels,
FBandwidthIncoming,
FBandwidthOutgoing
);
end else begin
// for client
FMaxPeer:=1;
FHost:=enet_host_create(nil,
FMaxPeer,
FMaxChannels,
FBandwidthIncoming,
FBandwidthOutgoing
);
end;
Result:= FHost<>nil;
end;
procedure TENetClass.DeInitHost;
begin
if FHost<>nil then
enet_host_destroy(FHost);
FHost:=nil;
end;
function TENetClass.Connect(const Host: string; Port: Word): Boolean;
begin
Result:=False;
if not FIsServer then begin
DisConnect(True);
InitHost;
enet_address_set_host(@FAddress,PAnsiChar(Host));
FAddress.port:=Port;
FClientData:=Random(MaxInt);
FPeer:=enet_host_connect(FHost,@FAddress,FMaxChannels,FClientData);
Result:=FPeer<>nil;
if Result then
if (enet_host_service(FHost,@FEvent,FConnectTimeout)>0) and
(FEvent.kind=ENET_EVENT_TYPE_CONNECT) then begin
Result:=True;
if Assigned(FEventConnect) then
FEventConnect(FEvent);
end else begin
enet_peer_reset(FPeer);
FPeer:=nil;
DeInitHost;
end;
end;
end;
function TENetClass.DisConnect(bNow:Boolean): Boolean;
begin
Result:=False;
if (not FIsServer) and (FHost<>nil) then begin
if FPeer<>nil then begin
if bNow then
enet_peer_disconnect_now(FPeer,FClientData)
else
enet_peer_disconnect(FPeer,FClientData);
FPeer:=nil;
end;
Result:=True;
end;
DeInitHost;
end;
function TENetClass.SendMsg(Channel: Byte; Data: Pointer; Length: Integer;
flag: TENetPacketFlags; WaitResponse: Boolean): Boolean;
var
FPacket : pENetPacket;
PacketFlag : Cardinal;
begin
Result:=False;
if FPeer<>nil then begin
PacketFlag:=GetPacketFlag(flag);
FPacket := enet_packet_create(Data, Length, PacketFlag);
if enet_peer_send(FPeer,Channel,FPacket)=0 then
if WaitResponse then
Result:=ProcessMsg;
end;
end;
function TENetClass.SendMsgEventPeer(Data: Pointer; Length: Integer;
flag: TENetPacketFlags; WaitResponse: Boolean = False): Boolean;
var
FPacket : pENetPacket;
PacketFlag : Cardinal;
begin
Result:=False;
if FEvent.Peer<>nil then begin
PacketFlag:=GetPacketFlag(flag);
FPacket := enet_packet_create(Data, Length, PacketFlag);
if enet_peer_send(FEvent.Peer,FEvent.channelID,FPacket)=0 then
if WaitResponse then
Result:=ProcessMsg;
end;
end;
procedure TENetClass.FlushMsg;
begin
if FHost<>nil then
enet_host_flush(FHost);
end;
function TENetClass.BroadcastMsg(Channel: Byte; Data: Pointer; Length: Integer;
flag: TENetPacketFlags; WaitResponse: Boolean): Boolean;
var
FPacket : pENetPacket;
PacketFlag : Cardinal;
begin
Result:=False;
if FPeer<>nil then begin
PacketFlag:=GetPacketFlag(flag);
FPacket:= enet_packet_create(Data, Length, PacketFlag);
enet_host_widecast(FHost,Channel,FPacket);
if WaitResponse then
Result:=ProcessMsg;
end;
end;
function TENetClass.ProcessMsg: Boolean;
var
broadcast : Boolean;
bdChannel : Byte;
packet : pENetPacket;
pflag : Integer;
svcres : integer;
begin
Result := False;
if FHost<>nil then
begin
SvcRes:=enet_host_service(FHost,@FEvent,FMessageTimeout);
if SvcRes>0 then
begin
case FEvent.kind of
ENET_EVENT_TYPE_NONE : if Assigned(FEventNone) then
FEventNone(FEvent);
ENET_EVENT_TYPE_CONNECT : if Assigned(FEventConnect) then
FEventConnect(FEvent);
ENET_EVENT_TYPE_DISCONNECT : if Assigned(FEventDisConnect) then
FEventDisConnect(FEvent);
ENET_EVENT_TYPE_RECEIVE : begin
try
if FIsServer then begin
broadcast:=True;
pflag:=FEvent.packet^.flags;
bdChannel:= FEvent.channelID;
end;
if Assigned(FEventReceive) then
FEventReceive(FEvent,broadcast,bdChannel);
if FIsServer and broadcast then begin
packet := enet_packet_create(FEvent.packet^.data,FEvent.packet^.dataLength,pflag);
enet_host_widecast(FHost,bdChannel,packet);
end;
finally
enet_packet_destroy(FEvent.packet);
end;
end;
else ;
end;
Result := True;
end;
end;
end;
procedure TENetClass.Ping;
begin
if (not FIsServer) and (FPeer<>nil) then
enet_peer_ping(FPeer);
end;
end.