Luasocket series: Luasocket Hello world!

Source: Internet
Author: User


Luasocket Introduction:

Luasocket is a Lua extension library This is composed by the parts:
A C core, provides support for the TCP and U DP transport layers, and a set of LUA modules that add support for functionality commonly needed by applications that deal With the Internet.

The core support have been implemented so it's both efficient and simple to use. It was available to any Lua application once it had been properly initialized by the interpreter in USE. 
The Code Have been tested and runs well on several Windows and Unix platforms.

Luasocket version 2.0.2 is now available for download! It is compatible with Lua 5.1, and have been tested on Windows XP, Linux, and Mac OS x.
2.0.2 is just a bug-fix/update R Elease. The
Luasocket is an extended library of Lua. Includes two sections: the C language is written to provide the core modules of the TCP and UDP transport layer protocols and to support the processing of network LUA modules. The
core modules are efficient and simple to implement. It can be used just by embedding the LUA interpreter. Core modules have been tested and run on multiple Windows and UNIX operating systems. The
Luasocket 2.0.2 version is compatible with LUA version 5.1.x and has been tested on Windows XP, Linux and Mac OS X operating systems. The
Luasocket is released as a bug fix release.


Luasocket using:

This article uses the Windows 7 operating system and uses the VS2010 tool. So just test the Winsock API section.

1, when importing header files and source files, remove the files under the relevant UNIX conduct system such as Usocket.

2 Add #pragma comment (lib, "Ws2_32.lib") to Wsocket.h to import the Winsock library, otherwise the socket API-related function will be found during link.


The contents of the Luasocketsample.cpp file are as follows:

extern "C" {#include "lua.h" #include "lauxlib.h" #include "lualib.h" #include "luasocket.h"//Use Luasocket library only need to include header files. }int Main (int argc, char **argv) {     //create lua_state  lua_state *l = Lua_open ();  /* Create state *  //Register standard library  lual_openlibs (L);  Register Luasocket Library  luaopen_socket_core (L);  Execute Sample_1.lua  lual_dofile (L, "Luasocketsample.lua");  Close Lua_state  lua_close (L);          return 1;}

In the Luasocket source code example, the following example is taken from the Echosrvr.lua file and partially modified:

Local host = host or "127.0.0.1" local port = port or 8080print ("Binding to Host"). Host: "' and port". Port.. "...")--create UDP object UDP = Assert (SOCKET.UDP ())--bind to the specified port assert (Udp:setsockname (host, Port))--set timeout period assert (UDP: SetTimeout (5))--Gets the bound IP and port IP, port = udp:getsockname () assert (IP, port) print ("Waiting Packets on": Ip.. ":" .. Port.. "...") local recvmaxbyte =20--single-threaded infinite loop while 1 do    --Receive UDP Packetdgram, IP, port = udp:receivefrom (Recvmaxbyte) if (dgram = = "Terminate") then    print ("Terminate") Breakendif Dgram thenprint ("Echoing"). Dgram. "To". Ip.. ":" .. Port)--Send data Udp:sendto (Dgram, IP, port) Else        print (IP)    endendudp=nilcollectgarbage ("collect")

The results of the operation are as follows:



The code is very simple for luasocket files to be included with LUASOKCT.

/*=========================================================================** LuaSocket toolkit* Networking Support for the Lua language* Diego nehab* 26/11/1999** This library are part of a effort to progressively increase the N  etwork* connectivity of the Lua language. The Lua interface to networking* functions follows the Sockets API closely, trying to simplify all tasks* involved in Setting up both client and server connections. The provided* IO routines, however, follow the LUA style, being very similar to the* standard Lua Read and write Functio ns.** RCS ID: $Id: luasocket.c,v 1.53 2005/10/07 04:40:59 Diego Exp $\*=================================================  ========================*//*=========================================================================** Standard Include files\*=========================================================================*/#include "lua.h" # Include "Lauxlib.h" #if!defined (lua_version_num) | | (Lua_version_num < 501) #include "compAt-5.1.h "#endif/*=========================================================================** LuaSocket includes\ *=========================================================================*/#include "luasocket.h" #include " Auxiliar.h "#include" except.h "#include" timeout.h "#include" buffer.h "#include" inet.h "#include" tcp.h "#include" Udp.h "#include" select.h "/*-------------------------------------------------------------------------* * Internal function prototypes\*-------------------------------------------------------------------------*/static int Global _skip (lua_state *l); static int global_unload (lua_state *l); static int Base_open (lua_state *l);/*--------------------- ----------------------------------------------------* * Modules and functions\*----------------------------------- --------------------------------------*///This is the function of all LUA modules provided by luasocket static const Lual_reg mod[] ={{"Auxiliar", auxilia R_open}, {"Except", Except_open}, {"Timeout", Timeout_open}, {"Buffer", Buffer_open}, {"inet", Inet_open}, {"TCP", Tcp_open}, {"UDP", Udp_open}, {"Select", Select_open}, {NULL, null}};static Lual_reg func[] ={{"Skip", Global_skip}, {"__unload", Global_unload}, {NULL, null}};/*------------ -------------------------------------------------------------* * Skip a few arguments\*----------------------------     ---------------------------------------------*/static int Global_skip (lua_state *l) {int amount = Lual_checkint (L, 1);    int ret = Lua_gettop (L)-amount-1; return ret >= 0? ret:0;} /*-------------------------------------------------------------------------* * Unloads the library\*--------------    -----------------------------------------------------------*/static int global_unload (lua_state *l) {(void) L;    Socket_close (); return 0;} /*-------------------------------------------------------------------------* * Setup basic stuff.\*--------------- ----------------------------------------------------------*/static int BASE_open (lua_state *l) {//By judging the socket base provided by different operating systems, the window operating system is using the winsock2.0 version if (Socket_open ()) {/* Export function s (and leave namespace table on top of stack) *///register luasocket to _g["socket" Lual_openlib (L, "socket", func, 0); #ifde        F luasocket_debug lua_pushstring (L, "_DEBUG");        Lua_pushboolean (L, 1);        Lua_rawset (L,-3); #endif/* Make version string available to scripts */lua_pushstring (L, "_version");        Lua_pushstring (L, luasocket_version);        Lua_rawset (L,-3);    return 1;        } else {lua_pushstring (L, "Unable to initialize library");        Lua_error (L);    return 0; }}/*-------------------------------------------------------------------------* * Initializes all library modules.\* -------------------------------------------------------------------------*///using Luasocket, Luaopen_socket_core () function to register all related modules.    Luasocket_api int Luaopen_socket_core (lua_state *l) {int i;    Base_open (L); for (i = 0; mod[i].name; i++) Mod[i].func (L); return 1;}

Summary:

Luasocket as a network development repository for LUA, the use of luasocket can be cross-platform. Can be used under Windows, UNIX, and Mac operating systems. Below the window platform, Luasocket only uses 14 header files.

The number of source code lines is greater than 1000 lines to 2000 rows. Library is small, easy to understand learning. Under the window operating system, only the Select IO model is used. Like the Java Nio layer is the select that encapsulates the Windows conduct system

IO model. In the learning process, you can use the smallest understanding to learn if you encapsulate a socket network library. That's a great thing. There are also luasocket libraries that provide a small and practical function with no extra code. The Socket core is provided via Wsocket and Usocket, and UDP and TCP protocols are implemented by separate files. I hope to learn from the Luasocket library to better understand learning to encapsulate their own network library.

At the same time, Luasocket provides an object-oriented programming approach, so we can continue to review the previous LUA and C interaction sections. If the interaction between LUA and C is not well understood, there will be a lot of obstacles in learning the luasocket part.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Luasocket series: Luasocket Hello world!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.