Documentation
¶
Overview ¶
Package rpc provides access to the exported methods of an object across a network or other I/O connection. After creating a server instance objects can be registered, making it visible from the outside. Exported methods that follow specific conventions can be called remotely. It also has support for the publish/subscribe pattern.
Methods that satisfy the following criteria are made available for remote access:
- object must be exported
- method must be exported
- method returns 0, 1 (response or error) or 2 (response and error) values
- method argument(s) must be exported or builtin types
- method returned value(s) must be exported or builtin types
An example method:
func (s *CalcService) Add(a, b int) (int, error)
When the returned error isn't nil the returned integer is ignored and the error is send back to the client. Otherwise the returned integer is send back to the client.
Optional arguments are supported by accepting pointer values as arguments. E.g. if we want to do the addition in an optional finite field we can accept a mod argument as pointer value.
func (s *CalService) Add(a, b int, mod *int) (int, error)
This RPC method can be called with 2 integers and a null value as third argument. In that case the mod argument will be nil. Or it can be called with 3 integers, in that case mod will be pointing to the given third argument. Since the optional argument is the last argument the RPC package will also accept 2 integers as arguments. It will pass the mod argument as nil to the RPC method.
The server offers the ServeCodec method which accepts a ServerCodec instance. It will read requests from the codec, process the request and sends the response back to the client using the codec. The server can execute requests concurrently. Responses can be sent back to the client out of order.
An example server which uses the JSON codec:
type CalculatorService struct {}
func (s *CalculatorService) Add(a, b int) int {
return a + b
}
func (s *CalculatorService Div(a, b int) (int, error) {
if b == 0 {
return 0, errors.New("divide by zero")
}
return a/b, nil
}
calculator := new(CalculatorService)
server := NewServer()
server.RegisterName("calculator", calculator")
l, _ := net.ListenUnix("unix", &net.UnixAddr{Net: "unix", Name: "/tmp/calculator.sock"})
for {
c, _ := l.AcceptUnix()
codec := v2.NewJSONCodec(c)
go server.ServeCodec(codec)
}
The package also supports the publish subscribe pattern through the use of subscriptions. A method that is considered eligible for notifications must satisfy the following criteria:
- object must be exported
- method must be exported
- first method argument type must be context.Context
- method argument(s) must be exported or builtin types
- method must return the tuple Subscription, error
An example method:
func (s *BlockChainService) NewBlocks(ctx context.Context) (Subscription, error) {
...
}
Subscriptions are deleted when:
- the user sends an unsubscribe request
- the connection which was used to create the subscription is closed. This can be initiated by the client and server. The server will close the connection on an write error or when the queue of buffered notifications gets too big.
Index ¶
- Constants
- Variables
- func CreateIPCListener(endpoint string) (net.Listener, error)
- func NewHTTPServer(cors []string, vhosts []string, srv *Server) *http.Serverdeprecated
- func NewWSServer(allowedOrigins []string, srv *Server) *http.Serverdeprecated
- type API
- type BatchElem
- type BlockNumber
- type Client
- func Dial(rawurl string) (*Client, error)
- func DialContext(ctx context.Context, rawurl string) (*Client, error)
- func DialHTTP(endpoint string) (*Client, error)
- func DialHTTPWithClient(endpoint string, client *http.Client) (*Client, error)
- func DialIPC(ctx context.Context, endpoint string) (*Client, error)
- func DialInProc(handler *Server) *Client
- func DialWebsocket(ctx context.Context, endpoint, origin string) (*Client, error)
- func (c *Client) BatchCall(b []BatchElem) error
- func (c *Client) BatchCallContext(ctx context.Context, b []BatchElem) error
- func (c *Client) Call(result interface{}, method string, args ...interface{}) error
- func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
- func (c *Client) Close()
- func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
- func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
- func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, ...) (*ClientSubscription, error)
- func (c *Client) SupportedModules() (map[string]string, error)
- type ClientSubscription
- type CodecOption
- type Error
- type ID
- type Notifier
- type RPCService
- type Server
- func (s *Server) RegisterName(name string, rcvr interface{}) error
- func (s *Server) ServeCodec(codec ServerCodec, options CodecOption)
- func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (srv *Server) ServeListener(l net.Listener) error
- func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption)
- func (s *Server) Stop()
- func (srv *Server) WebsocketHandler(allowedOrigins []string) http.Handler
- type ServerCodec
- type Subscription
Examples ¶
Constants ¶
const ( PendingBlockNumber = BlockNumber(-2) LatestBlockNumber = BlockNumber(-1) EarliestBlockNumber = BlockNumber(0) )
const MetadataApi = "rpc"
Variables ¶
var ( ErrClientQuit = errors.New("client is closed") ErrNoResult = errors.New("no result in JSON-RPC response") ErrSubscriptionQueueOverflow = errors.New("subscription queue overflow") )
var ( //当连接不支持通知时,将返回ErrNotificationsUnsupported // ErrNotificationsUnsupported is returned when the connection doesn't support notifications ErrNotificationsUnsupported = errors.New("notifications not supported") //找不到给定id的通知时返回ErrNotificationNotFound // ErrNotificationNotFound is returned when the notification for the given id is not found ErrSubscriptionNotFound = errors.New("subscription not found") )
Functions ¶
func CreateIPCListener ¶
CreateIPCListener创建一个监听器,在Unix平台上,这是一个unix套接字 Windows这是一个命名管道 CreateIPCListener creates an listener, on Unix platforms this is a unix socket, on Windows this is a named pipe
func NewWSServer
deprecated
Types ¶
type API ¶
type API struct {
Namespace string // namespace under which the rpc methods of Service are exposed
Version string // api version for DApp's
Service interface{} // receiver instance which holds the methods持有方法的接收器实例
Public bool // indication if the methods must be considered safe for public use
}
API描述了通过RPC接口提供的一组方法 API describes the set of methods offered over the RPC interface
type BatchElem ¶
type BatchElem struct {
Method string
Args []interface{}
//结果已解组到此字段中。 必须将结果设置为所需类型的非零指针值,否则将丢弃响应。
// The result is unmarshaled into this field. Result must be set to a
// non-nil pointer value of the desired type, otherwise the response will be
// discarded.
Result interface{}
//如果服务器为此请求返回错误,或者如果解组为Result失败,则会设置错误。 它没有设置I / O错误。
// Error is set if the server returns an error for this request, or if
// unmarshaling into Result fails. It is not set for I/O errors.
Error error
}
BatchElem是批处理请求中的元素。 BatchElem is an element in a batch request.
type BlockNumber ¶
type BlockNumber int64
func (BlockNumber) Int64 ¶
func (bn BlockNumber) Int64() int64
func (*BlockNumber) UnmarshalJSON ¶
func (bn *BlockNumber) UnmarshalJSON(data []byte) error
UnmarshalJSON将给定的JSON片段解析为BlockNumber。 它支持: - “latest”,“early”或“pending”作为字符串参数 - 块号 返回错误: 当给定参数不是已知字符串时出现无效块号错误 当给定的块号太小或太大时超出范围错误 UnmarshalJSON parses the given JSON fragment into a BlockNumber. It supports: - "latest", "earliest" or "pending" as string arguments - the block number Returned errors: - an invalid block number error when the given argument isn't a known strings - an out of range error when the given block number is either too little or too large
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
/Client表示到RPC服务器的连接。 Client represents a connection to an RPC server.
func Dial ¶
Dial为给定的URL创建一个新客户端。 当前支持的URL方案是“http”,“https”,“ws”和“wss”。 如果rawurl是 没有URL方案的文件名,使用UNIX建立本地套接字连接 Windows上支持的平台和命名管道上的域套接字。 如果你想 配置传输选项,改为使用DialHTTP,DialWebsocket或DialIPC。 对于websocket连接,原点设置为本地主机名。 如果连接丢失,客户端将自动重新连接。 Dial creates a new client for the given URL.
The currently supported URL schemes are "http", "https", "ws" and "wss". If rawurl is a file name with no URL scheme, a local socket connection is established using UNIX domain sockets on supported platforms and named pipes on Windows. If you want to configure transport options, use DialHTTP, DialWebsocket or DialIPC instead.
For websocket connections, the origin is set to the local host name.
The client reconnects automatically if the connection is lost.
func DialContext ¶
DialContext创建一个新的RPC客户端,就像Dial一样。 上下文用于取消或超时初始连接建立。 它不会影响与客户端的后续交互。 DialContext creates a new RPC client, just like Dial.
The context is used to cancel or time out the initial connection establishment. It does not affect subsequent interactions with the client.
func DialHTTP ¶
DialHTTP创建一个新的RPC客户端,通过HTTP连接到RPC服务器。 DialHTTP creates a new RPC client that connects to an RPC server over HTTP.
func DialHTTPWithClient ¶
DialHTTPWithClient创建一个新的RPC客户端,使用提供的HTTP客户端通过HTTP连接到RPC服务器。 DialHTTPWithClient creates a new RPC client that connects to an RPC server over HTTP using the provided HTTP Client.
func DialIPC ¶
RPC的IPC服务,拨号的实现方法 DialIPC create a new IPC client that connects to the given endpoint. On Unix it assumes the endpoint is the full path to a unix socket, and Windows the endpoint is an identifier for a named pipe.
The context is used for the initial connection establishment. It does not affect subsequent interactions with the client. DialIPC创建一个连接到给定端点的新IPC客户端。 在Unix上,它假定端点是unix套接字的完整路径,而Windows端点是命名管道的标识符。 上下文用于初始连接建立。 它不会影响与客户端的后续交互。
func DialInProc ¶
拨号的实现方法 NewInProcClient attaches an in-process connection to the given RPC server.NewInProcClient将进程内连接附加到给定的RPC服务器。
func DialWebsocket ¶
DialWebsocket创建一个与JSON-RPC服务器通信的新RPC客户端 正在侦听给定端点。 上下文用于初始连接建立。 它不会影响与客户端的后续交互。 DialWebsocket creates a new RPC client that communicates with a JSON-RPC server that is listening on the given endpoint.
The context is used for the initial connection establishment. It does not affect subsequent interactions with the client.
func (*Client) BatchCall ¶
BatchCall将所有给定的请求作为单个批处理发送,并等待服务器 为所有人返回一个回复。 与Call相反,BatchCall仅返回I / O错误。 任何特定的错误 通过相应BatchElem的Error字段报告请求。 请注意,批处理调用可能无法在服务器端以原子方式执行。 BatchCall sends all given requests as a single batch and waits for the server to return a response for all of them.
In contrast to Call, BatchCall only returns I/O errors. Any error specific to a request is reported through the Error field of the corresponding BatchElem.
Note that batch calls may not be executed atomically on the server side.
func (*Client) BatchCallContext ¶
BatchCall将所有给定的请求作为单个批处理发送,并等待服务器 为所有人返回一个回复。 等待时间受限于 上下文的截止日期。 与CallContext相反,BatchCallContext仅返回已发生的错误 发送请求时 通过以下方式报告特定于请求的任何错误 相应BatchElem的错误字段。 请注意,批处理调用可能无法在服务器端以原子方式执行。 BatchCall sends all given requests as a single batch and waits for the server to return a response for all of them. The wait duration is bounded by the context's deadline.
In contrast to CallContext, BatchCallContext only returns errors that have occurred while sending the request. Any error specific to a request is reported through the Error field of the corresponding BatchElem.
Note that batch calls may not be executed atomically on the server side.
func (*Client) Call ¶
Call使用给定的参数执行JSON-RPC调用,如果没有发生错误,则将其解封为/结果。/结果必须是指针,以便包json可以解组到其中。您/也可以传递零,在这种情况下,结果将被忽略。 Call performs a JSON-RPC call with the given arguments and unmarshals into result if no error occurred.
The result must be a pointer so that package json can unmarshal into it. You can also pass nil, in which case the result is ignored.
func (*Client) CallContext ¶
func (c *Client) CallContext(ctx context.Context, result interface{}, method string, args ...interface{}) error
CallContext使用给定的参数执行JSON-RPC调用。 如果是上下文 在调用成功返回之前取消,CallContext立即返回。 结果必须是一个指针,以便包json可以解组。 您 也可以传递nil,在这种情况下会忽略结果。 CallContext performs a JSON-RPC call with the given arguments. If the context is canceled before the call has successfully returned, CallContext returns immediately.
The result must be a pointer so that package json can unmarshal into it. You can also pass nil, in which case the result is ignored.
func (*Client) Close ¶
func (c *Client) Close()
关闭关闭客户端,中止任何正在进行的请求。 Close closes the client, aborting any in-flight requests.
func (*Client) EthSubscribe ¶
func (c *Client) EthSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
Eth Subscribe在“eth”命名空间下注册订阅。 EthSubscribe registers a subscripion under the "eth" namespace.
func (*Client) ShhSubscribe ¶
func (c *Client) ShhSubscribe(ctx context.Context, channel interface{}, args ...interface{}) (*ClientSubscription, error)
Shh Subscribe在“shh”命名空间下注册订阅。 ShhSubscribe registers a subscripion under the "shh" namespace.
func (*Client) Subscribe ¶
func (c *Client) Subscribe(ctx context.Context, namespace string, channel interface{}, args ...interface{}) (*ClientSubscription, error)
订阅使用给定的参数调用“<namespace> _subscribe”方法, 注册订阅 订阅的服务器通知是 发送到指定频道。 通道的元素类型必须匹配 订阅返回的预期内容类型。 context参数取消设置订阅的RPC请求,但在Subscribe返回后对订阅没有影响。 最终将放弃缓慢的订阅者。 客户端最多可缓冲8000个通知 在考虑用户死亡之前 订阅Err频道将收到 ErrSubscriptionQueueOverflow。 在通道上使用足够大的缓冲区或确保 通道通常至少有一个阅读器来防止出现此问题。 Subscribe calls the "<namespace>_subscribe" method with the given arguments, registering a subscription. Server notifications for the subscription are sent to the given channel. The element type of the channel must match the expected type of content returned by the subscription.
The context argument cancels the RPC request that sets up the subscription but has no effect on the subscription after Subscribe has returned.
Slow subscribers will be dropped eventually. Client buffers up to 8000 notifications before considering the subscriber dead. The subscription Err channel will receive ErrSubscriptionQueueOverflow. Use a sufficiently large buffer on the channel or ensure that the channel usually has at least one reader to prevent this issue.
type ClientSubscription ¶
type ClientSubscription struct {
// contains filtered or unexported fields
}
Subscriptions. ClientSubscription表示通过EthSubscribe建立的订阅。 A ClientSubscription represents a subscription established through EthSubscribe.
Example ¶
package main
import (
"context"
"fmt"
"math/big"
"time"
"github.com/ethereum/go-ethereum/rpc"
)
//在这个例子中,我们的客户端会跟踪最新的“块号”
//服务器已知 服务器支持两种方法:
//
// eth_getBlockByNumber(“latest”,{})
//返回最新的块对象。
//
// eth_subscribe(“newBlocks”)
//创建一个订阅,在新块到达时触发块对象。
// In this example, our client whishes to track the latest 'block number'
// known to the server. The server supports two methods:
//
// eth_getBlockByNumber("latest", {})
// returns the latest block object.
//
// eth_subscribe("newBlocks")
// creates a subscription which fires block objects when new blocks arrive.
type Block struct {
Number *big.Int
}
func main() {
// Connect the client.
client, _ := rpc.Dial("ws://127.0.0.1:8546")
subch := make(chan Block)
//确保subch收到最新的块。
// Ensure that subch receives the latest block.
go func() {
//for i := 0; ; i++ {
// if i > 0 {
// time.Sleep(2 * time.Second)
//}
subscribeBlocks(client, subch)
//}
}()
//在订阅到达时打印订阅的事件。
// Print events from the subscription as they arrive.
for block := range subch {
fmt.Println("latest block:", block.Number)
}
}
// subscribeBlocks在自己的goroutine中运行并维护
// 订阅新块。
// subscribeBlocks runs in its own goroutine and maintains
// a subscription for new blocks.
func subscribeBlocks(client *rpc.Client, subch chan Block) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
//订阅新块。
// Subscribe to new blocks.
sub, err := client.EthSubscribe(ctx, subch, "newBlocks")
if err != nil {
fmt.Println("subscribe error:", err)
return
}
//现在建立连接。
//使用当前块更新通道。
// The connection is established now.
// Update the channel with the current block.
var lastBlock Block
if err := client.CallContext(ctx, &lastBlock, "eth_getBlockByNumber", "latest"); err != nil {
fmt.Println("can't get latest block:", err)
return
}
subch <- lastBlock
// The subscription will deliver events to the channel. Wait for the
// subscription to end for any reason, then loop around to re-establish
// the connection.
fmt.Println("connection lost: ", <-sub.Err())
}
Output:
func (*ClientSubscription) Err ¶
func (sub *ClientSubscription) Err() <-chan error
Err返回订阅错误频道。 Err的预期用途是安排 意外关闭客户端连接时重新订阅 错误通道在订阅结束时收到一个值 错误 如果已调用Close,则收到的错误为nil 在底层客户端上,没有发生其他错误。 在订阅上调用Unsubscribe时,将关闭错误通道。 Err returns the subscription error channel. The intended use of Err is to schedule resubscription when the client connection is closed unexpectedly.
The error channel receives a value when the subscription has ended due to an error. The received error is nil if Close has been called on the underlying client and no other error has occurred.
The error channel is closed when Unsubscribe is called on the subscription.
func (*ClientSubscription) Unsubscribe ¶
func (sub *ClientSubscription) Unsubscribe()
取消订阅取消订阅通知并关闭错误频道。 可以安全地多次调用它。 Unsubscribe unsubscribes the notification and closes the error channel. It can safely be called more than once.
type CodecOption ¶
type CodecOption int
CodecOption指定此编解码器支持的消息类型 CodecOption specifies which type of messages this codec supports
const ( //OptionMethodInvocation表示编解码器支持RPC方法调用 // OptionMethodInvocation is an indication that the codec supports RPC method calls OptionMethodInvocation CodecOption = 1 << iota // OptionSubscriptions表示编解码器支持RPC通知 // OptionSubscriptions is an indication that the codec suports RPC notifications OptionSubscriptions = 1 << iota // support pub sub )
type ID ¶
type ID string
ID defines a pseudo random number that is used to identify RPC subscriptions.
type Notifier ¶
type Notifier struct {
// contains filtered or unexported fields
}
Notifier对支持订阅的RPC连接很紧张。 服务器回调使用通知程序发送通知。 Notifier is tight to a RPC connection that supports subscriptions. Server callbacks use the notifier to send notifications.
func NotifierFromContext ¶
NotifierFromContext返回存储在ctx中的Notifier值(如果有)。 NotifierFromContext returns the Notifier value stored in ctx, if any.
func (*Notifier) Closed ¶
func (n *Notifier) Closed() <-chan interface{}
Closed returns a channel that is closed when the RPC connection is closed.
func (*Notifier) CreateSubscription ¶
func (n *Notifier) CreateSubscription() *Subscription
CreateSubscription返回与RPC连接耦合的新订阅。 默认情况下,订阅处于非活动状态,并且在订阅标记为活动之前会删除通知。 这是在将订阅ID发送到客户端之后由RPC服务器完成的。 CreateSubscription returns a new subscription that is coupled to the RPC connection. By default subscriptions are inactive and notifications are dropped until the subscription is marked as active. This is done by the RPC server after the subscription ID is send to the client.
type RPCService ¶
type RPCService struct {
// contains filtered or unexported fields
}
RPCService提供有关服务器的元信息。 例如 提供有关加载模块的信息。 RPCService gives meta information about the server. e.g. gives information about the loaded modules.
func (*RPCService) Modules ¶
func (s *RPCService) Modules() map[string]string
Modules返回RPC服务列表及其版本号 Modules returns the list of RPC services with their version number
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
服务器代表一个RPC服务器 Server represents a RPC server
func NewServer ¶
func NewServer() *Server
NewServer将创建一个没有注册处理程序的新服务器实例。 NewServer will create a new server instance with no registered handlers.
func (*Server) RegisterName ¶
RegisterName将为给定名称下的给定rcvr类型创建一个服务。 如果给定的rcvr上没有方法匹配条件是RPC方法或预订,则返回错误。 否则,会创建一个新服务并将其添加到此服务器实例所服务的服务集合中。 RegisterName will create a service for the given rcvr type under the given name. When no methods on the given rcvr match the criteria to be either a RPC method or a subscription an error is returned. Otherwise a new service is created and added to the service collection this server instance serves.
func (*Server) ServeCodec ¶
func (s *Server) ServeCodec(codec ServerCodec, options CodecOption)
ServeCodec从编解码器读取传入请求,调用相应的回调并使用给定的编解码器将响应写回。 它会阻止,直到编解码器关闭或服务器停止。 无论哪种情况,编解码器都会关闭。订阅消息,不会自动关闭 ServeCodec reads incoming requests from codec, calls the appropriate callback and writes the response back using the given codec. It will block until the codec is closed or the server is stopped. In either case the codec is closed.
func (*Server) ServeHTTP ¶
func (srv *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves JSON-RPC requests over HTTP.
func (*Server) ServeListener ¶
ServeListener接受l上的连接,为它们提供JSON-RPC。 ServeListener accepts connections on l, serving JSON-RPC on them.
func (*Server) ServeSingleRequest ¶
func (s *Server) ServeSingleRequest(codec ServerCodec, options CodecOption)
这个方法和上面的那个方法刚好相反,是同步处理请求的,等处理结束后,整个过程才会结束。此结束不提供codec.Close()方法,不用想也该明白,同步结束了,后面该干嘛就干嘛。 ServeSingleRequest从给定的编解码器中读取和处理单个RPC请求。 除非发生不可恢复的错误,否则它不会关闭编解码器。 注意,此方法将在处理单个请求后返回! ServeSingleRequest reads and processes a single RPC request from the given codec. It will not close the codec unless a non-recoverable error has occurred. Note, this method will return after a single request has been processed! 参数codec中存储的是客户端发来的请求,经过处理后,会将响应结果写入codec中并返回给客户端。 该方法处理完codec中的内容后,会调用codec.Close()接口方法,处理请求结束时候的一些操作。 注意,看s.serveRequest(codec, false, options),里面的false表示该方法是并发处理请求的
func (*Server) Stop ¶
func (s *Server) Stop()
Stop将停止读取新请求,等待stopPendingRequestTimeout允许挂起的请求完成, 关闭所有将取消待处理请求/订阅的编解码器。 Stop will stop reading new requests, wait for stopPendingRequestTimeout to allow pending requests to finish, close all codecs which will cancel pending requests/subscriptions.
func (*Server) WebsocketHandler ¶
WebsocketHandler返回一个为WebSocket连接提供JSON-RPC的处理程序。 allowedOrigins应该是逗号分隔的允许源URL列表。 要允许与任何来源的连接,请传递“*”。 WebsocketHandler returns a handler that serves JSON-RPC to WebSocket connections.
allowedOrigins should be a comma-separated list of allowed origin URLs. To allow connections with any origin, pass "*".
type ServerCodec ¶
type ServerCodec interface {
// Read next request//读取下一个请求
ReadRequestHeaders() ([]rpcRequest, bool, Error)
// Parse request argument to the given types解析给定类型的请求参数
ParseRequestArguments(argTypes []reflect.Type, params interface{}) ([]reflect.Value, Error)
// Assemble success response, expects response id and payload组装成功响应,期望响应ID和有效负载
CreateResponse(id interface{}, reply interface{}) interface{}
// Assemble error response, expects response id and error组装错误响应,期望响应ID和错误
CreateErrorResponse(id interface{}, err Error) interface{}
// Assemble error response with extra information about the error through info通过信息汇总错误响应以及有关错误的额外信息
CreateErrorResponseWithInfo(id interface{}, err Error, info interface{}) interface{}
// Create notification response创建通知响应
CreateNotification(id, namespace string, event interface{}) interface{}
// Write msg to client.写信息给客户端。
Write(msg interface{}) error
// Close underlying data stream关闭底层数据流
Close()
// Closed when underlying connection is closed底层连接关闭时关闭
Closed() <-chan interface{}
}
ServerCodec实现读取,解析和编写RPC会话服务器端的RPC消息。 由于编解码器可以同时在多个go-routine中调用,因此实现必须安全地执行。 ServerCodec implements reading, parsing and writing RPC messages for the server side of a RPC session. Implementations must be go-routine safe since the codec can be called in multiple go-routines concurrently.
func NewCodec ¶
func NewCodec(rwc io.ReadWriteCloser, encode, decode func(v interface{}) error) ServerCodec
NewCodec基于明确给定的编码和解码方法创建一个新的RPC服务器编解码器,支持JSON-RPC 2.0。 NewCodec creates a new RPC server codec with support for JSON-RPC 2.0 based on explicitly given encoding and decoding methods.
func NewJSONCodec ¶
func NewJSONCodec(rwc io.ReadWriteCloser) ServerCodec
NewJSONCodec创建一个支持JSON-RPC 2.0的新RPC服务器编解码器。 NewJSONCodec creates a new RPC server codec with support for JSON-RPC 2.0.
type Subscription ¶
type Subscription struct {
ID ID
// contains filtered or unexported fields
}
订阅者由通知程序创建并紧密通知该通知程序。 客户可以使用 此订阅等待客户端的取消订阅请求,请参阅Err()。 a Subscription is created by a notifier and tight to that notifier. The client can use this subscription to wait for an unsubscribe request for the client, see Err().
func (*Subscription) Err ¶
func (s *Subscription) Err() <-chan error
Err returns a channel that is closed when the client send an unsubscribe request.