C#使用TcpListener及TcpClient開(kāi)發(fā)一個(gè)簡(jiǎn)單的Chat工具實(shí)例
本文使用的開(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è)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#實(shí)現(xiàn)對(duì)二維數(shù)組排序的方法
這篇文章主要介紹了C#實(shí)現(xiàn)對(duì)二維數(shù)組排序的方法,實(shí)例分析了C#數(shù)組遍歷與排序的相關(guān)技巧,需要的朋友可以參考下2015-06-06
C# Directory.GetFiles()函數(shù)案例詳解
這篇文章主要介紹了C# Directory.GetFiles()函數(shù)案例詳解,本篇文章通過(guò)簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
C#實(shí)現(xiàn)把指定數(shù)據(jù)寫入串口
這篇文章主要介紹了C#實(shí)現(xiàn)把指定數(shù)據(jù)寫入串口,直接給出示例代碼,需要的朋友可以參考下2015-06-06
c#同步兩個(gè)子目錄文件示例分享 兩個(gè)文件夾同步
這篇文章主要介紹了使用c#同步兩個(gè)子目錄文件的方法,大家參考使用吧2014-01-01
Unity實(shí)現(xiàn)紅酒識(shí)別的示例代碼
本文主要介紹了如何通過(guò)Unity實(shí)現(xiàn)紅酒識(shí)別,可以實(shí)現(xiàn)識(shí)別圖像中的紅酒標(biāo)簽,返回紅酒名稱、國(guó)家、產(chǎn)區(qū)、酒莊、類型、糖分、葡萄品種、酒品描述等信息,感興趣的可以學(xué)習(xí)一下2022-02-02
C#實(shí)現(xiàn)進(jìn)制轉(zhuǎn)換
這篇文章介紹了C#實(shí)現(xiàn)進(jìn)制轉(zhuǎn)換的方法,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05

