[C#]使用TcpListener及TcpClient開發一個簡單的Chat工具


 


本文為原創文章、源代碼為原創代碼,如轉載/復制,請在網頁/代碼處明顯位置標明原文名稱、作者及網址,謝謝!


 

本文使用的開發環境是VS2017及dotNet4.0,寫此隨筆的目的是給自己及新開發人員作為參考,

本例子比較簡單,使用的是控制台程序開發,若需要使用該軟件作為演示,必須先運行服務端,再運行客戶端。

因為是首次接觸該方面的知識,寫得比較簡陋,如有更好的建議,請提出,謝謝!

一、編寫服務器端代碼,如下:

using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace ChatServer
{
    class Program
    {
        static void Main(string[] args)
        {
            bool cancel = false;
            byte[] buffer = new byte[1024];
            string message;
            byte[] messageBytes;
            int count = 0;
            TcpListener tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, 13000));
            tcpListener.Start();
            Console.WriteLine("Waiting for a connection... ");
            TcpClient tcpClient = tcpListener.AcceptTcpClient();
            Console.WriteLine("Connected.");
            NetworkStream stream = tcpClient.GetStream();
           
           Task.Factory.StartNew(() => 
            {
                while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Reply from server {tcpClient.Client.LocalEndPoint.ToString()}:{Encoding.UTF8.GetString(buffer, 0, count)}");
                }
            });
                   
            Task t = Task.Factory.StartNew(() => 
            {
                while(!cancel)
                {
                    message = Console.ReadLine();
                    if (message.ToUpper() == "Y")
                    {
                        cancel = true;
                        return;
                    }
                    messageBytes = Encoding.UTF8.GetBytes(message);
                    stream.Write(messageBytes, 0, messageBytes.Length);
                }
            });
                      
            if (cancel) tcpClient.Close();
                
            while (true)
            {
                if (t != null && t.IsCompleted) break;
            }
        }
    }
}

二、編寫客戶端代碼,如下:

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

namespace ChatClient
{
    class Program
    {
        static void Main(string[] args)
        {
            bool cancel = false;
            byte[] buffer = new byte[1024];
            string message;
            byte[] messageBytes;
            int count = 0;
            try
            {
                TcpClient tcpClient = new TcpClient(new IPEndPoint(Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(p => p.AddressFamily == AddressFamily.InterNetwork).First(), 14000));
                tcpClient.Connect(new IPEndPoint(IPAddress.Parse("192.168.94.26"), 13000));
                NetworkStream stream = tcpClient.GetStream();
                
                Task.Factory.StartNew(() =>
                {
                    while ((count = stream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        Console.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss fff} Reply from client {tcpClient.Client.LocalEndPoint.ToString()}:{Encoding.UTF8.GetString(buffer, 0, count)}");
                    }
                });
                Task t = Task.Factory.StartNew(() =>
                {
                    while (!cancel)
                    {
                        message = Console.ReadLine();
                        if (message.ToUpper() == "Y")
                        {
                            cancel = true;
                            return;
                        }
                        messageBytes = Encoding.UTF8.GetBytes(message);
                        stream.Write(messageBytes, 0, messageBytes.Length);
                        Thread.Sleep(10);
                    }
                });
                if (cancel) tcpClient.Close();
               
                while (true)
                {
                    if (t != null && t.IsCompleted) break;
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
         }   
    }
}

三、先運行服務端代碼,后再另外一台電腦運行客戶端代碼,效果圖如下:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM