国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > C# > 正文

C#使用TcpListener及TcpClient開(kāi)發(fā)一個(gè)簡(jiǎn)單的Chat工具實(shí)例

2020-01-24 00:23:10
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

本文使用的開(kāi)發(fā)環(huán)境是VS2017及dotNet4.0,寫此隨筆的目的是給自己及新開(kāi)發(fā)人員作為參考,

本例子比較簡(jiǎn)單,使用的是控制臺(tái)程序開(kāi)發(fā),若需要使用該軟件作為演示,必須先運(yùn)行服務(wù)端,再運(yùn)行客戶端。

因?yàn)槭鞘状谓佑|該方面的知識(shí),寫得比較簡(jiǎn)陋,如有更好的建議,請(qǐng)?zhí)岢觯x謝!

一、編寫服務(wù)器端代碼,如下:

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();   }   }  }}

三、先運(yùn)行服務(wù)端代碼,后再另外一臺(tái)電腦運(yùn)行客戶端代碼,效果圖如下:

以上這篇C#使用TcpListener及TcpClient開(kāi)發(fā)一個(gè)簡(jiǎn)單的Chat工具實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 枣阳市| 永宁县| 平陆县| 鄂托克旗| 宜兴市| 岢岚县| 惠来县| 正定县| 广西| 清流县| 博湖县| 黄浦区| 新田县| 资阳市| 环江| 宁强县| 巴青县| 景泰县| 同德县| 航空| 易门县| 丰顺县| 莲花县| 呼和浩特市| 靖边县| 梅河口市| 新安县| 青岛市| 晋城| 仁化县| 古交市| 方城县| 南木林县| 河南省| 太白县| 龙州县| 竹溪县| 文登市| 上犹县| 延边| 普洱|