CÁC GIẢI PHÁP LẬP TRÌNH C# - Trang 468

468
Chương 11: Lập trình mạng

// Định nghĩa endpoint (thông điệp được gửi tại đây).

Console.Write("Connect to IP: ");

string IP = Console.ReadLine();

Console.Write("Connect to port: ");

int port = Int32.Parse(Console.ReadLine());

IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP),

port);

// Định nghĩa endpoint cục bộ (thông điệp được nhận tại đây).

Console.Write("Local port for listening: ");

localPort = Int32.Parse(Console.ReadLine());

Console.WriteLine();

// Tạo một tiểu trình mới để nhận thông điệp đến.

Thread receiveThread = new Thread(

new ThreadStart(ReceiveData));

receiveThread.IsBackground = true;

receiveThread.Start();

UdpClient client = new UdpClient();

try {

string text;

do {

text = Console.ReadLine();

if (text != "") {

// Mã hóa dữ liệu thành dạng nhị phân

// bằng phép mã hóa UTF8.

byte[] data = Encoding.UTF8.GetBytes(text);

// Gửi text đến client ở xa.

client.Send(data, data.Length, remoteEndPoint);