socket.*

类型
版本 发布版本 2024.3703
关键字 套接字、LuaSocket、网络
另请参阅 LuaSocket 文档
network.request()
network.download()
network.canDetectNetworkStatusChanges
network.setStatusListener()

概述

重要信息

socket 库提供对主机设备上网络堆栈的低级访问。它适用于常规网络使用(使用 network 库更容易)。只有少数特定任务需要 socket API,但这些任务并不常见,并且需要很少见的网络编程专业知识。任何使用 socket API 的代码都需要持续调整,因为设备供应商会更改网络访问规则,例如关于 IPv6 网络的规则,而使用 network API 编写的代码通常会继续正常运行,因为它受到设备供应商的直接支持。

Solar2D 目前包含 LuaSocket 库的版本3.0-rc1这些 Lua 模块实施常见的网络协议,例如 SMTP、HTTP 和 FTP。还包括支持 MIME(常见的编码)、URL 处理和 LTN12 以传输和过滤数据的特性。

有关异步 HTTP 函数(而非同步 LuaSocket 函数),请参阅 network.request()network.download()

陷阱

在 Android 上,你必须将 INTERNET 权限添加到 build.settings 文件中。

settings =
{
   android =
   {
      usesPermissions =
      {
         "android.permission.INTERNET",
      },
   },
}

示例

获取 IP 地址和端口
local socket = require( "socket" )

-- Connect to the client
local client = socket.connect( "www.apple.com", 80 )
-- Get IP and port from client
local ip, port = client:getsockname()
 
-- Print the IP address and port to the terminal
print( "IP Address:", ip )
print( "Port:", port )
从远程 URL 下载图像
-- Load the relevant LuaSocket modules
local http = require( "socket.http" )
local ltn12 = require( "ltn12" )
 
-- Create local file for saving data
local path = system.pathForFile( "hello.png", system.DocumentsDirectory )
myFile = io.open( path, "w+b" ) 
 
-- Request remote file and save data to local file
http.request{
    url = "http://solar2d.cn/wordpress/wp-content/uploads/2018/07/orange_vertikal_RGB.png", 
    sink = ltn12.sink.file( myFile )
}
 
-- Display local file
local testImage = display.newImage( "hello.png", system.DocumentsDirectory )