Network Programming with C# Exceed Camp #2, CPE, KU Day 3

Download Report

Transcript Network Programming with C# Exceed Camp #2, CPE, KU Day 3

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)

Connectionless, unreliable transport layer
protocol
Application
UDP
IP
UDP Ports


16-bit unsigned integers associated with
UDP connection
Used to distinguish different processes
running on the same host
Proc1
Proc2
A
IP Address 1
Ports
Internet
Proc3
Proc4
Proc5
B
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
Bind socket to
the endpoint
Receive data
Close socket
Close socket
Creating UDP Socket

The following namespaces should be used
using System.Net;
using System.Net.Sockets;
using System.Text;

Use new keyword to create an object of
class Socket
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
block
s
Start
ReceiveFrom()
new Thread
:
:
block
s
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


ทำงำนคล้ำยโปรแกรมเดำะบอล แต่เล่นสองคน
แต่ละคนผลัดกันเดำะบอล ใครพลำดก่อนแพ้