建立连接
在介绍通信协议的时候,实际上服务侧对socket
或者name_pipe
的监听基本上也概括到了。
接下来客户侧连接上unix domain socket
或者name_pipe
,一个通信通道就建立完成了。
searpc-named-pipe-transport.c
int searpc_named_pipe_client_connect(SearpcNamedPipeClient *client)
{
#if !defined(WIN32)
client->pipe_fd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un servaddr;
servaddr.sun_family = AF_UNIX;
g_strlcpy (servaddr.sun_path, client->path, sizeof(servaddr.sun_path));
if (connect(client->pipe_fd, (struct sockaddr *)&servaddr, (socklen_t)sizeof(servaddr)) < 0) {
g_warning ("pipe client failed to connect to server: %s\n", strerror(errno));
return -1;
}
#else // !defined(WIN32)
SearpcNamedPipe pipe_fd;
pipe_fd = CreateFile(
client->path, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
if (pipe_fd == INVALID_HANDLE_VALUE) {
G_WARNING_WITH_LAST_ERROR("Failed to connect to named pipe");
return -1;
}
DWORD mode = PIPE_READMODE_MESSAGE;
if (!SetNamedPipeHandleState(pipe_fd, &mode, NULL, NULL)) {
G_WARNING_WITH_LAST_ERROR("Failed to set named pipe mode");
return -1;
}
client->pipe_fd = pipe_fd;
#endif // !defined(WIN32)
/* g_debug ("pipe client connected to server\n"); */
return 0;
}
named_pipe.py
class NamedPipeTransport(SearpcTransport):
"""
This transport uses named pipes on windows and unix domain socket
on linux/mac.
It's compatible with the c implementation of named pipe transport.
in lib/searpc-named-pipe-transport.[ch] files.
The protocol is:
- request: <32b length header><json request>
- response: <32b length header><json response>
"""
def __init__(self, socket_path):
self.socket_path = socket_path
self.pipe = None
def connect(self):
self.pipe = socket.socket(socket.AF_UNIX)
self.pipe.connect(self.socket_path)
def stop(self):
if self.pipe:
self.pipe.close()
self.pipe = None
通道已建立完毕,接下来的就是在通道上进行数据的往来了。
seafile
的web
客户端就是通过python
客户端与seafile-server
的c
服务端建立通道,进行消息通讯的。