Movatterモバイル変換


[0]ホーム

URL:


Fork me on GitHub
Tweet

lua-enet

lua-enet is a binding to theENet library forLua. ENet is a thin network communication layer over UDP that provides highperformance and reliable communication that is suitable for games. Theinterface exposes an asynchronous way of creating clients and servers that iseasy to integrate into existing event loops.

To get an idea of how ENet works and what it provides have a look atFeatures and Achritecture from theoriginal documentation.

Download & Install

Linux & OSX

Before installinglua-enet, you must make sure you haveENet installed. Consult your system’s packagemanagement.

If you've gotLua Rocks then installation is veryeasy:

$luarocks install enet

Otherwise you can download the source can from GitHub:https://github.com/leafo/lua-enet

Windows

Prebuilt binaries are provided:

Downloadhttp://leafo.net/lua-enet/bin/lua-enet-1.1.zip.
Unzip and install alongside your Lua installation.

Tutorial

We'll need a client and a server. A server is ahost bound to an address.A client is an unboundhost that connects to an address.enet.host_create is used to create a new host.host:service is used to waitfor events and send packets. It can optionally have a specified timeout.

Whenhost:service receives an event it returns an event object, which is aplain Lua table. Thetype entry holds the kind of event as a string, and thepeer entry has the associated peer who triggered the event.

Using this information, we can make a simple echo server:

-- server.luarequire"enet"localhost=enet.host_create"localhost:6789"whiletruedolocalevent=host:service(100)ifeventandevent.type=="receive"thenprint("Got message: ",event.data,event.peer)event.peer:send(event.data)endend

Data, whether sent or received, is always a Lua string. Primitive types can beconverted to a binary string to reduce the number of bytes sent by using a binaryserialization library.

The client for our server can be written like so:

-- client.luarequire"enet"localhost=enet.host_create()localserver=host:connect("localhost:6789")localdone=falsewhilenotdonedolocalevent=host:service(100)ifeventthenifevent.type=="connect"thenprint("Connected to",event.peer)event.peer:send("hello world")elseifevent.type=="receive"thenprint("Got message: ",event.data,event.peer)done=trueendendendserver:disconnect()host:flush()

Upon receiving the connect message we send"hello world" to the server, thenwait for the response.

When a client disconnects, make sure to calldisconnect on the server object,and then tell the host to flush (unlesshost:service will be called again)otherwise the server will have to wait for the client to disconnect from timeout.

Reference

enet.host_create([bind_address, peer_count, channel_count, in_bandwidth, out_bandwidth])

Returns a new host. All arguments are optional.

Abind_address ofnil makes a host that can not be connected to (typicallya client). Otherwise the address can either be of the form<ipaddress>:<port>,<hostname>:<port>, or*:<port>.

Example addresses include"127.0.0.1:8888","localhost:2232", and"*:6767".

Parameters:

host:connect(address [, channel_count, data])

Connects a host to a remote host. Returns peer object associated with remotehost. The actual connection will not take place until the nexthost:serviceis done, in which a"connect" event will be generated.

channel_count is the number of channels to allocate. It should be the same asthe channel count on the server. Defaults to1.

data is an integer value that can be associated with the connect event.Defaults to0.

host:service([timeout])

Wait for events, send and receive any ready packets.timeout is the maxnumber of milliseconds to be waited for an event. By defaulttimeout is0.Returnsnil on timeout if no events occurred.

If an event happens, an event table is returned. All events have atype entry,which is one of"connect","disconnect", or"receive". Events also have apeer entry which holds the peer object of who triggered the event.

A"receive" event also has adata entry which is a Lua string containing thedata received.

host:check_events()

Checks for any queued events and dispatches one if available. Returns theassociated event if something was dispatched, otherwisenil.

host:compress_with_range_coder()

Enables an adaptive order-2 PPM range coder for the transmitted data ofall pers.

host:flush()

Sends any queued packets. This is only required to send packets earlier thanthe next call tohost:service, or ifhost:service will not be called again.

host:broadcast(data [, channel, flag])

Queues a packet to be sent to all connected peers. Seepeer:send for arguments.

host:channel_limit(limit)

Sets the maximum number of channels allowed. If it is0 then the systemmaximum allowable value is used.

host:bandwidth_limit(incoming, outgoing)

Sets the bandwidth limits of the host in bytes/sec. Set to0 for unlimited.

host:total_sent_data()

Returns the number of bytes that were sent through the given host.

host:total_received_data()

Returns the number of bytes that were received by the given host.

host:service_time()

Returns the timestamp of the last call to host:service() or host:flush().

host:peer_count()

Returns the number of peers that are allocated for the given host. Thisrepresents the maximum number of possible connections.

host:get_peer(index)

Returns the connected peer at the specified index (starting at 1). ENetstores all peers in an array of the corresponding host and re-uses unusedpeers for new connections. You can query the state of a peer usingpeer:state.

host:get_socket_address()

Returns a string that describes the socket address of the given host. Thestring is formatted as “a.b.c.d:port”, where “a.b.c.d” is the ip address ofthe used socket.

peer:connect_id()

Returns the field ENetPeer::connectID that is assigned for eachconnection.

peer:disconnect([data])

Requests a disconnection from the peer. The message is sent on the nexthost:service orhost:flush.

data is optional integer value to be associated with the disconnect.

peer:disconnect_now([data])

Force immediate disconnection from peer. Foreign peer not guaranteed to receivedisconnect notification.

data is optional integer value to be associated with the disconnect.

peer:disconnect_later([data])

Request a disconnection from peer, but only after all queued outgoing packetsare sent.

data is optional integer value to be associated with the disconnect.

peer:index()

Returns the index of the peer. All peers of an ENet host are kept in anarray. This function finds and returns the index of the peer of its hoststructure.

peer:ping()

Send a ping request to peer, updatesround_trip_time. This is calledautomatically at regular intervals.

peer:ping_interval(interval)

Specifies the interval in milliseconds that pings are sent to the otherend of the connection (defaults to 500).

peer:reset()

Forcefully disconnects peer. The peer is not notified of the disconnection.

peer:send(data [, channel, flag])

Queues a packet to be sent to peer.data is the contents of the packet, itmust be a Lua string.

channel is the channel to send the packet on. Defaults to0.

flag is one of"reliable","unsequenced", or"unreliable". Reliablepackets are guaranteed to arrive, and arrive in the order in which they are sent.Unsequenced packets are unreliable and have no guarantee on the order theyarrive. Defaults to reliable.

peer:state()

Returns the state of the peer as a string. This can be any of thefollowing:

peer:receive()

Attempts to dequeue an incoming packet for this peer.Returnsnil if there are no packets waiting. Otherwise returns two values:the string representing the packet data, and the channel the packet came from.

peer:round_trip_time([value])

Returns or sets the current round trip time (i.e. ping). If value is nilthe current value of the peer is returned. Otherwise the value roundTripTimeis set to the specified value and returned.

Enet performs some filtering on the round trip times and it takes some timeuntil the parameters are accurate.

peer:last_round_trip_time([value])

Returns or sets the round trip time of the previous round trip timecomputation. If value is nil the current value of the peer is returned.Otherwise the value lastRoundTripTime is set to the specified value andreturned.

Enet performs some filtering on the round trip times and it takessome time until the parameters are accurate. To speed it up you can setthe value of the last round trip time to a more accurate guess.

peer:throttle_configure(interval, acceleration, deceleration)

Changes the probability at which unreliable packets should not be dropped.

Parameters:

(limit, minimum, maximum) peer:timeout(limit, minimum, maximum)

Returns or sets the parameters when a timeout is detected. This is happenseither after a fixed timeout or a variable timeout of time that takes theround trip time into account. The former is specified with themaximumparameter.

Parameters:

See official ENet documentation for detailed description.

License (MIT)

Copyright (C) 2011 by Leaf CorcoranPermission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, 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 INTHE SOFTWARE.

Contact

Author: Leaf Corcoran (leafo) (@moonscript)
Email:leafot@gmail.com
Homepage:http://leafo.net

Generated on Mon Aug 19 08:54:45 2013

[8]ページ先頭

©2009-2025 Movatter.jp