1. 程式人生 > >UDP聊天室

UDP聊天室

客戶端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace UDP協議_客戶端
{
    class Program
    {
        static void Main(string[] args)
        {
            //建立Socket
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            while (true)
            {
                //傳送資料
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);

                EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.3.41"), 7788);
                udpClient.SendTo(data, serverPoint);
            }

            udpClient.Close();
            Console.ReadKey();
        }
    }
}

伺服器端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace UDP協議_伺服器端
{
    class Program
    {
        private static Socket udpServer;

        static void Main(string[] args)
        {
            //建立Socket
            udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
           
            //繫結ip跟埠
            udpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.3.41"), 7788));

            //接收資料
            //開啟執行緒
            new Thread(ReceiveMessage) { IsBackground=true}.Start();//IsBackground後臺執行緒

           // udpServer.Close();
            Console.ReadKey();
        }

        static void ReceiveMessage()
        {
            while (true)
            {
                //接收資料
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);//資料的來源
                byte[] data = new byte[1024];
                int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);//ref表示 udpServer.ReceiveFrom可以對 remoteEndPoint做修改
                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("從ip:" + (remoteEndPoint as IPEndPoint).Address.ToString() + ":" + (remoteEndPoint as IPEndPoint).Port.ToString() + "收到了資料:" + message);

            }
            
        }

    }
}