390 likes | 735 Vues
Network Programming with C#. Exceed Camp #2, CPE, KU Day 3. Outline. Socket Programming Threading in C#. Socket Overview. Socket Class Provides a rich set of methods and properties for network communications. User Datagram Protocol (UDP)
E N D
Network Programming with C# Exceed Camp #2, CPE, KUDay 3
Outline • Socket Programming • Threading in C#
Socket Overview • Socket Class • Provides a rich set of methods and properties for network communications. • User Datagram Protocol (UDP) • Connectionless, unreliable transport layer protocol Application UDP IP
Internet Proc4 Ports Proc3 Proc2 Proc1 Proc5 UDP Ports • 16-bit unsigned integers associated with UDP connection • Used to distinguish different processes running on the same host A B IP Address 1 IP Address 2
Using UDP Sockets To receive data To send data Create a UDP socket Create a UDP socket Create a local endpoint(Local IP + Local Port) Send data Close socket Bind socket tothe endpoint Receive data Close socket
Creating UDP Socket • The following namespaces should be used • Use new keyword to create an object of class Socket using System.Net; using System.Net.Sockets; using System.Text; Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Creating Local Endpoint • Resolve local IP addresses using functions Dns.Resolve() and Dns.GetHostName() • Create an endpoint at the first IP address and port 11000 IPHostEntry hostEntry = Dns.Resolve(Dns.GetHostName()); IPEndPoint endPoint = new IPEndPoint(hostEntry.AddressList[0], 11000); Note: port number can be anything above 1023
Binding Socket to Endpoint • Make the socket wait for incoming data at the endpoint created previously s.Bind(endPoint);
Receiving Data • Another endpoint is prepared to store remote endpoint information • ReceiveFrom() will block until data is received IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0); EndPoint senderRemote = (EndPoint)sender; byte[] msg = new Byte[256]; Console.WriteLine("Waiting for data..."); s.ReceiveFrom(msg, ref senderRemote);
Sending Data • Another endpoint is created to specify the receiver IP address and UDP port byte[] msg = Encoding.ASCII.GetBytes("This is a test"); Console.WriteLine("Sending data."); s.SendTo(msg, new IPEndPoint(IPAddress.Parse("10.0.0.2"), 11000));
Closing Socket • When no longer used, the socket must be closed s.Close();
Threading • ReceiveFrom() is blocking • I.e., it waits until data is received Start Start blocks blocks ReceiveFrom() new Thread : : ReceiveFrom() : One thread of control Two threads of control
Creating Thread • For convenient, use System.Threading namespace using System.Threading; void ThreadProc() { : while (true) { s.ReceiveFrom(...); } } void MainProc() { : Thread t = new Thread(new ThreadStart(ThreadProc)); t.IsBackground = true; t.Start(); : }
Assignment • โปรแกรม NetBall • ทำงานคล้ายโปรแกรมเดาะบอล แต่เล่นสองคน • แต่ละคนผลัดกันเดาะบอล ใครพลาดก่อนแพ้