我是unix域套接字的新手(但对于套接字的一般概念并不是全新的),并试图让用Python编写的服务器与用C编写的客户端进行通信,以了解有关它们的更多信息。我使用了https://pymotw.com/2/socket/uds.html和http://beej.us/guide/bgipc/output/html/multipage/unixsock.html中的代码示例。根据我的理解,它们应该是兼容的。我唯一改变的是套接字路径,因此它们是相同的。但是,当我尝试连接它们时(尽管它们位于同一目录中并且python服务器创建了套接字文件),客户端无法找到套接字文件的路径。当我使用Python服务器和客户端或C套接字和客户端时,它工作得很好,但我需要它与Python服务器和C客户端一起工作。我正在运行OS X,使用Python 2.7作为服务器并使用gcc编译客户端。
编辑: 这是我的服务器代码:
import socket
import sys
import os
server_address = 'echo_socket'
# Make sure the socket does not already exist
try:
os.unlink(server_address)
except OSError:
if os.path.exists(server_address):
raise
# Create a UDS socket
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Bind the socket to the port
print >>sys.stderr, 'starting up on %s' % server_address
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1)
while True:
# Wait for a connection
print >>sys.stderr, 'waiting for a connection'
connection, client_address = sock.accept()
try:
print >>sys.stderr, 'connection from', client_address
# Receive the data in small chunks and retransmit it
while True:
data = connection.recv(100)
print >>sys.stderr, 'received "%s"' % data
if data:
print >>sys.stderr, 'sending data back to the client'
connection.sendall(data)
else:
print >>sys.stderr, 'no more data from', client_address
break
finally:
# Clean up the connection
connection.close()
这是我的客户代码:
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#define SOCK_PATH "echo_socket"
int main(void)
{
int s, t, len;
struct sockaddr_un remote;
char str[100];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
printf("Trying to connect...\n");
remote.sun_family = AF_UNIX;
strcpy(remote.sun_path, SOCK_PATH);
len = strlen(remote.sun_path) + sizeof(remote.sun_family);
if (connect(s, (struct sockaddr *)&remote, len) == -1) {
perror("connect");
exit(1);
}
printf("Connected.\n");
while(printf("> "), fgets(str, 100, stdin), !feof(stdin)) {
if (send(s, str, strlen(str), 0) == -1) {
perror("send");
exit(1);
}
if ((t=recv(s, str, 100, 0)) > 0) {
str[t] = '\0';
printf("echo> %s", str);
} else {
if (t < 0) perror("recv");
else printf("Server closed connection\n");
exit(1);
}
}
close(s);
return 0;
}
由于我没有使用UDS的经验,我很感激您的帮助。
提前致谢!