开发者

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

I'm trying to adapt this python code I found for connecting to the Dropbox daemon:

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

Here is what I have so far:

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;
}

This compiles fine, but when I try to run it, I get System.Net.Sockets.SocketException: No such host is known. I assume this is because cmdSocket and ifaceSocket are paths, not IP addreses. Python appears to handle this automatically, how do I do it in C#? This is my first foray into socket programming, so please point out any obvious mistakes.


You need to use Mono.Unix.UnixEndPoint from Mono.Posix.dll instead of an IPEndPoint. Everything else is the same. See an example of how XSP uses it here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜