在c#中创建套接字的代码

时间:2015-12-14 13:36:53

标签: c# sockets

我正在尝试使用局域网内的三台计算机创建服务器和客户端网络。我已经阅读了有关如何创建服务器 - 客户端通信的以下post。我想知道这些代码行在下面的示例中执行了什么:

// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

// Create a TCP/IP socket.
Socket listener = new  
Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp );

我不熟悉网络资料。我不明白这些行是否创建了一个具有特定IP和端口的套接字,它等待客户端的响应。客户端套接字是否有相应的示例?

编辑:我有以下设置。三台带有三个kinect 2的计算机运行一个c#项目,该项目捕获kinect流并将其存储到硬盘上。我希望当在服务器中按下记录时,可以同时记录来自所有运动的流。

EDIT2:我正在尝试运行客户端版本,但收到以下错误:

enter image description here

1 个答案:

答案 0 :(得分:6)

在您发布的链接中,还有一个Asynchronous Client Socket example。这不是你想要的吗?

// Connect to a remote device.
try {
    // Establish the remote endpoint for the socket.
    // The name of the 
    // remote device is "host.contoso.com".
    IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

    // Create a TCP/IP socket.
    Socket client = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp);

    // Connect to the remote endpoint.
    client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client);
    connectDone.WaitOne();

    // Send test data to the remote device.
    Send(client,"This is a test<EOF>");
    sendDone.WaitOne();

    // Receive the response from the remote device.
    Receive(client);
    receiveDone.WaitOne();

    // Write the response to the console.
    Console.WriteLine("Response received : {0}", response);

    // Release the socket.
    client.Shutdown(SocketShutdown.Both);
    client.Close();

} catch (Exception e) {
    Console.WriteLine(e.ToString());
}