Chương trình UDP đơn giản

2 233 3
Chương trình UDP đơn giản

Đang tải... (xem toàn văn)

Thông tin tài liệu

Chương trình UDP đơn giản (Server/Client) Cùng làm chương trình đơn giản sử dụng UDP để gửi thông điệp Đầu tiên viết Client gửi thông điệp tới server PHP Code: using using using using System; System.Net; System.Net.Sockets; System.Text; namespace MyUdpClient { class TestUdpClient { public static void Main() { // tạo đối tượng MyUdpClient MyUdpClient client = new MyUdpClient(); // thực kết nối gửi thông điệp client.OnConnect(); } } #region === CLASS: MyUdpClient === class MyUdpClient { // Method public void OnConnect() { // thông tin host để kết nối string _host = "127.0.0.1"; // thông tin port connect int _port = 2008; // tạo UDP Object UdpClient udp = new UdpClient(); // kết nối tới host udp.Connect(_host, _port); // tạo data để gửi Luôn dạng Bytes :) Byte[] data = Encoding.ASCII.GetBytes("Xcross87 Client says hello to Server"); // gửi data tới host udp.Send(data,data.Length); } } #endregion } Bây ta viết UDP Server phải open port 2008 để listen connection tới thu nhận gói thông điệp từ client gửi đến PHP Code: using using using using System; System.Net; System.Net.Sockets; System.Text; namespace MyUdpServer { class TestUdpServer { public static void Main() { // tạo đối tượng MyUdpServer MyUdpServer server = new MyUdpServer(); // mở server để bắt đầu listen client server.OnStart(); } } #region === CLASS: MyUdpServer === class MyUdpServer { // Method public void OnStart() { // tạo đối tượng UdpClient lắng nghe cổng 2008 UdpClient udp = new UdpClient(2008); // thực listen liên tục while (true) { // xác định điểm Remote IP IPEndPoint RemoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0) ; // thu lấy thông tin từ client dạng byte Byte[] data = udp.Receive(ref RemoteIPEndPoint); // chuyển string string message = Encoding.ASCII.GetString(data); // in thông điệp Console.WriteLine("Address: {0} - Message: {1}", RemoteIPEndPo int.Address, message); } } } } sau bật Server lên để im bật Client lên bạn thấy kết thông điệp ý muốn ... TestUdpServer { public static void Main() { // tạo đối tượng MyUdpServer MyUdpServer server = new MyUdpServer(); // mở server để bắt đầu listen client server.OnStart(); } } #region === CLASS: MyUdpServer... #region === CLASS: MyUdpServer === class MyUdpServer { // Method public void OnStart() { // tạo đối tượng UdpClient lắng nghe cổng 2008 UdpClient udp = new UdpClient(2008); // thực listen liên tục... RemoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0) ; // thu lấy thông tin từ client dạng byte Byte[] data = udp. Receive(ref RemoteIPEndPoint); // chuyển string string message = Encoding.ASCII.GetString(data);

Ngày đăng: 03/12/2015, 22:50

Tài liệu cùng người dùng

Tài liệu liên quan