Skynet's C API uses asynchronous read and write, you can use C calls, listen on a port, or initiate a TCP connection. However, the specific operation result waits for the Skynet event callback. The Skynet sends the result as a PTYPE_SOCKET
type of message to the service initiating the request. (Refer to Skynet_socket.h)
Such an API is difficult to use in dealing with real business, so it provides a set of blocking-mode LUA APIs for reading and writing TCP sockets. It is the encapsulation of the C API.
The so-called blocking pattern is actually taking advantage of the LUA coroutine mechanism. When you call the socket API, the service may be suspended (the time slice is ceded to other business processes), and the result is returned by the socket message, and the coroutine will continue executing.
Socketchannel
The request response pattern is one of the most common patterns used when interacting with an external service. There are two common ways to design protocols.
Each request packet corresponds to a response packet, which is guaranteed by the TCP protocol timing. The Redis protocol is a classic. Each Redis request must have a response, but it is not necessary to receive a response to send the next request.
Each request is initiated with a unique session ID, which is taken with this identity when sending a response. This design can not require that each request must have a response, and does not have to follow the first request to respond to the timing. This is how MongoDB's communication protocol is designed.
For the first mode, it is easy to implement with the Skynet socket API, but if you read and write a socket in a coroutine, the read process is blocked, which results in a decrease in throughput (the next request cannot be sent when the previous response is not received).
For the second mode, it is necessary to use skynet.fork to open a new thread to receive the response packet, and the corresponding to the request, the implementation is more cumbersome.
So, Skynet provides a higher-level package: Socket channel.
Specific usage of socket channel in addition to reading Lualib/socketchannel.lua (which is also a good material to understand the socket module), you can also read Lualib/redis.lua and lualib/ Mongo.lua These two database driver written for Skynet.
Mysql
In this fork https://github.com/chfg007/skynet, the driver of MySQL (from openresty) is realized.
Main documents for Lualib/mysql.lua and 3rd/lua-mysqlaux
Local status, Err = Pcall (MYSQLDB.QUERY,MYSQLDB,SQLSTR) Remember to catch the error, it is possible to query when the link has been disconnected.
Https://github.com/cloudwu/skynet/wiki/SocketChannel
Skynet Source Analysis: Socket