Tuesday, November 4, 2008

Tutor.com Classroom How-To #2: connecting to a TCP/IP Listener

These How-To tips are taken from The Tutor.com Classroom: Architecture and techniques using Silverlight, WPF, and the Microsoft .NET Framework.

You can check out the Silverlight Tutor.com Classroom in "practice" mode, although the real experience is with a live tutor on the other side!

Using the Socket class, we just need to create a SocketAsyncEventArgs and call ConnectAsync(). Notice an example of the “#if WPF” directive for subtle Silverlight/WPF differences (as described in the "Code Sharing" post) when we set the SocketAsyncEventArgs RemoteEndPoint.


public void Connect(string host, int port)
{
//instantiate socket
m_Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

//set up endpoint
#if WPF
m_SocketSendArgs.RemoteEndPoint = new IPEndPoint(Dns.GetHostAddresses(host)[0], port);
#else
m_SocketSendArgs.RemoteEndPoint = new DnsEndPoint(host, port);
#endif

//set up args
SocketAsyncEventArgs args = new SocketAsyncEventArgs();

args.UserToken = m_Socket;
args.RemoteEndPoint = m_SocketSendArgs.RemoteEndPoint;
args.Completed += new EventHandler(OnConnect);

m_Socket.ConnectAsync(args);
}

No comments: