您好,登錄后才能下訂單哦!
本文使用的開發環境是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(); } } } }
三、先運行服務端代碼,后再另外一臺電腦運行客戶端代碼,效果圖如下:
以上這篇C#使用TcpListener及TcpClient開發一個簡單的Chat工具實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。