当前位置:编程学习 > C#/ASP.NET >>

C#局域网聊天Demo

本demo使用C#编写,采用UDP协议。

分别建立发送、接收线程循环阻塞处理相应任务。


[csharp] 
using System; 
//using System.Collections.Generic; 
//using System.Linq; 
using System.Text; 
using System.Net; 
using System.Net.Sockets; 
using System.Threading; 
 
namespace UDPChat 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            //IPAddress[] t = Dns.GetHostAddresses(Dns.GetHostName());//在不同的局域网中获取的数量不一,请调试甄别 
            IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0].ToString().Length > 6 ? Dns.GetHostAddresses(Dns.GetHostName())[0] : Dns.GetHostAddresses(Dns.GetHostName())[1]; 
            IPEndPoint local = new IPEndPoint(ip, 8001); 
            bool isAlive = true; 
 
            UdpClient c= new UdpClient(local); 
             
            Thread s = new Thread(() => tSend(ref isAlive, c));//发送线程 
            s.Start(); 
            Thread r = new Thread(() => tRcv(ref isAlive, c));//接受线程 
            r.Start(); 
        } 
 
        static void tSend(ref bool isAlive, UdpClient c) 
        { 
            string input; 
            byte[] send; 
            IPEndPoint remote = null; 
            bool isAnIp = false; 
 
            while (!isAnIp) 
            { 
                Console.WriteLine("pls input an ip for this chat."); 
                input = Console.ReadLine(); 
                try 
                { 
                    remote = new IPEndPoint(IPAddress.Parse(input), 503); 
                    isAnIp = true; 
                } 
                catch 
                { 
                    Console.WriteLine("it is an invalid ip.\r\n"); 
                } 
            } 
            while (isAlive)  
            { 
                input = Console.ReadLine(); 
                if (input == "exit") 
                    isAlive = false; 
                send=Encoding.UTF8.GetBytes(input); 
                c.Send(send, send.Length, remote); 
                Console.WriteLine(); 
 
                Console.WriteLine("{0} sent:{1}", DateTime.Now.ToLocalTime().ToShortTimeString(), input); 
            } 
            c.Close(); 
            Console.WriteLine("quit chat."); 
            Console.ReadLine(); 
 
        } 
 
        static void tRcv(ref bool isAlive, UdpClient c) 
        { 
            byte[] rcv; 
            string receive; 
            IPEndPoint remote = new IPEndPoint(IPAddress.Any,0); 
 
            while (isAlive) 
            { 
                try 
                { 
                    rcv = c.Receive(ref remote); 
                } 
                catch 
                { 
                    break; 
                } 
 
                receive=Encoding.UTF8.GetString(rcv); 
                if (receive != "exit") 
                { 
  &n

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,