套接字通信C#

时间:2011-11-15 18:32:36

标签: c# sockets

我正在使用此类从/向我的应用程序发送Echo测试

public class SocketClient
{
    Socket socket = null;
    static ManualResetEvent clientDone = new ManualResetEvent(false);
    const int TIMEOUT_MILLISECONDS = 5000;
    const int MAX_BUFFER_SIZE = 2048;

    public SocketClient()
    {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    }

    public string Send(string serverName, int portNumber, string data)
    {
        string response = "Timeout";

        if (socket != null)
        {
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.RemoteEndPoint = new DnsEndPoint(serverName, portNumber);

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                response = e.SocketError.ToString();
                clientDone.Set();
            });

            byte[] payload = Encoding.UTF8.GetBytes(data);
            socketEventArg.SetBuffer(payload, 0, payload.Length);
            clientDone.Reset();
            socket.SendToAsync(socketEventArg);

            clientDone.WaitOne(TIMEOUT_MILLISECONDS);
        }
        else
        {
            response = "not initialized";
        }
        return response;
    }

    public string Recieve(int portNumber)
    {
        string response = "Timeout";

        if (socket != null)
        {
            SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
            socketEventArg.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);

            socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
            {
                if (e.SocketError == SocketError.Success)
                {
                    response = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
                    response.Trim('\0');
                }
                else
                {
                    response = e.SocketError.ToString();
                }

                clientDone.Set();
            });

            socketEventArg.RemoteEndPoint = new IPEndPoint(IPAddress.Any, portNumber);

            clientDone.Reset();

            socket.ReceiveFromAsync(socketEventArg);
            clientDone.WaitOne(TIMEOUT_MILLISECONDS);
        }

        return response;
    }

    public void Close()
    {
        socket.Close();
    }
}

以下是我如何使用它:

        SocketClient client = new SocketClient();
        client.Send("192.168.1.2",77 , "besm ellah");
        textBox1.Text=client.Recieve(77);

总是通过Argument Exception在socket.SendToAsync(socketEventArg);未处理 “参数remoteEP不能是DnsEndPoint类型。” “参数名称:remoteEP”

我在Windows功能上启用了简单TCP / IP的功能,但它也不起作用。

-UPDATE -

我尝试将代码更改为:

IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
socketEventArg.RemoteEndPoint = new IPEndPoint(localIPs[3], portNumber);

它不会给出异常,但是消息无法通过。

1 个答案:

答案 0 :(得分:1)

好吧,看起来您应该将其更改为不同类型的端点,而不是DNS端点。

我认为您应该使用IPEndPoint

http://msdn.microsoft.com/en-us/library/system.net.sockets.socketasynceventargs.aspx