2011-11-15 71 views
4

我使用這個類來/我的應用程序的Socket通信C#

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

它總是通過參數異常是未處理的socket.SendToAsync(socketEventArg); 「參數remoteEP不能是DnsEndPoint類型。」 「參數名稱:remoteEP」

我啓用了windows功能上的簡單TCP/IP功能,但它也不起作用。

-UPDATE-

我試圖改變的代碼是:

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

它沒有給出一個例外,但該消息沒有得到通過。

+0

我們可以得到的ArgumentException的細節?它應該告訴你那個異常中的參數有什麼問題。 – McKay

+0

@McKay,對不起,修正。 – SKandeel

+0

所以你沒有得到錯誤信息,什麼都沒有發生? – McKay

回答