溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C#使用TcpListener及TcpClient開發(fā)一個簡單的Chat工具實例

發(fā)布時間:2020-08-31 19:40:09 來源:腳本之家 閱讀:234 作者:cnc 欄目:編程語言

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

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

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

一、編寫服務(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ù)端代碼,后再另外一臺電腦運(yùn)行客戶端代碼,效果圖如下:

C#使用TcpListener及TcpClient開發(fā)一個簡單的Chat工具實例

C#使用TcpListener及TcpClient開發(fā)一個簡單的Chat工具實例

以上這篇C#使用TcpListener及TcpClient開發(fā)一個簡單的Chat工具實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI