繁体   English   中英

如何在C#中连接本地Socket?

[英]How do I connect to a local Socket in C#?

我正在尝试调整我找到的用于连接Dropbox守护程序的python代码:

def connect(self, cmd_socket="~/.dropbox/command_socket", iface_socket="~/.dropbox/iface_socket"):
    "Connects to the Dropbox command_socket, returns True if it was successfull."
    self.iface_sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    self.sck = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    try:
        self.sck.connect(os.path.expanduser(cmd_socket)) # try to connect
        self.iface_sck.connect(os.path.expanduser(iface_socket))
    except:
        self.connected = False
        return False
    else: # went smooth
        self.connected = True
        return True

这是我到目前为止:

public bool Connect (int port) {
    return Connect ("~/.dropbox/command_socket", "~/.dropbox/iface_socket",
                    port);
}

public bool Connect (string cmdSocket, string ifaceSocket, int port)
{
    IfaceSocket = new Socket (AddressFamily.Unix, SocketType.Stream,
                              ProtocolType.IP);
    CmdSocket = new Socket (AddressFamily.Unix, SocketType.Stream,
                            ProtocolType.IP);

    try {
        // ExpandUser replaces a leading "/~" with the user's home directory
        IPAddress [] CmdIPs = Dns.GetHostAddresses (ExpandUser (cmdSocket));
        CmdSocket.Connect (CmdIPs [0], port);
        IPAddress [] IfaceIPs = Dns.GetHostAddresses (ExpandUser (ifaceSocket));
        IfaceSocket.Connect (IfaceIPs [0], port);
    } catch (Exception e) {
        // Debug
        Console.WriteLine (e);

        Connected = false;
        return false;
    }

    Connected = true;
    return true;
}

这编译很好,但是当我尝试运行它时,我得到System.Net.Sockets.SocketException: No such host is known 我假设这是因为cmdSocketifaceSocket是路径,而不是IP地址。 Python似乎自动处理这个问题,我该如何在C#中执行此操作? 这是我第一次涉及套接字编程,所以请指出任何明显的错误。

您需要使用Mono.Unix.UnixEndPoint的Mono.Unix.UnixEndPoint而不是IPEndPoint。 其他一切都是一样的。 请参阅XSP如何在此处使用它的示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM