2009-08-03 104 views

回答

4
namespace SilverlightSocketClient 
{ 
    public partial class Page : UserControl 
    { 
     public Page() 
     { 
      InitializeComponent(); 
      this.Loaded += PageLoaded;  
     } 

     void PageLoaded(object sender, RoutedEventArgs e) 
     { 
      var endPoint = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4530); 
      var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 

      var args = new SocketAsyncEventArgs {UserToken = socket, RemoteEndPoint = endPoint}; 

      args.Completed += OnSocketConnectCompleted; 
      socket.ConnectAsync(args); 
     } 

     private void OnSocketConnectCompleted(object sender, SocketAsyncEventArgs e) 
     { 
      var response = new byte[1024]; 
      e.SetBuffer(response, 0, response.Length); 
      e.Completed -= OnSocketConnectCompleted; 
      e.Completed += OnSocketReceive; 
      var socket = (Socket)e.UserToken; 
      socket.ReceiveAsync(e); 
     } 

     private void OnSocketReceive(object sender, SocketAsyncEventArgs e) 
     { 
      StringReader sr = null; 
      try 
      { 
       string data = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred); 
       sr = new StringReader(data); 

       //Get data 
       if (data.Contains("Product")) 
       { 
        var xs = new XmlSerializer(typeof(Product)); 
        var product = (Product) xs.Deserialize(sr); 
        Dispatcher.BeginInvoke(UpdateOrder); 
       } 

       //Get another type of data 
       if (data.Contains("Order")) 
       { 
        var xs = new XmlSerializer(typeof(Order)); 
        var order = (Order)xs.Deserialize(sr); 
        var handler = new SomeEventHandler(UpdateOrder); 
        this.Dispatcher.BeginInvoke(handler, new object[] 
                  { 
                   order 
                  }); 
       } 
      } 
      catch (Exception ex) 
      { 
       //handle exception 
      } 
      finally 
      { 
       if (sr != null) sr.Close(); 
      } 

      //Prepare to receive more data 
      var socket = (Socket)e.UserToken; 
      socket.ReceiveAsync(e); 
     } 




    } 
}