我需要知道如何从Silverlight打开TCP套接字连接。怎么做?
答案 0 :(得分:4)
快速谷歌搜索提供此网站
答案 1 :(得分: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);
}
}
}
答案 2 :(得分:2)
查看Silverlight中的Socket
类。 MSDN documentation有一个很好的样本。