C#使用TcpListener及TcpClient開(kāi)發(fā)一個(gè)簡(jiǎn)單的Chat工具實(shí)例
本文使用的開(kāi)發(fā)環(huán)境是VS2017及dotNet4.0,寫(xiě)此隨筆的目的是給自己及新開(kāi)發(fā)人員作為參考,
本例子比較簡(jiǎn)單,使用的是控制臺(tái)程序開(kāi)發(fā),若需要使用該軟件作為演示,必須先運(yùn)行服務(wù)端,再運(yùn)行客戶(hù)端。
因?yàn)槭鞘状谓佑|該方面的知識(shí),寫(xiě)得比較簡(jiǎn)陋,如有更好的建議,請(qǐng)?zhí)岢?,謝謝!
一、編寫(xiě)服務(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;
}
}
}
}
二、編寫(xiě)客戶(hù)端代碼,如下:
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)行客戶(hù)端代碼,效果圖如下:


以上這篇C#使用TcpListener及TcpClient開(kāi)發(fā)一個(gè)簡(jiǎn)單的Chat工具實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
原生實(shí)現(xiàn)C#與Lua相互調(diào)用方法(Unity3D可用)
Lua是一種很好的擴(kuò)展性語(yǔ)言,Lua解釋器被設(shè)計(jì)成一個(gè)很容易嵌入到宿主程序的庫(kù),下面這篇文章主要給大家介紹了關(guān)于原生實(shí)現(xiàn)C#與Lua相互調(diào)用方法,Unity3D可用的相關(guān)資料,需要的朋友可以參考下2022-04-04
C#使用RabbitMQ發(fā)送和接收消息工具類(lèi)的實(shí)現(xiàn)
RabbitMQ是一個(gè)消息的代理器,用于接收和發(fā)送消息,本文主要介紹了C#使用RabbitMQ發(fā)送和接收消息工具類(lèi)的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-12-12
C#使用SqlConnection連接到SQL Server的代碼示例
這篇文章主要介紹了C#使用SqlConnection連接到SQL Server的代碼示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
C#實(shí)現(xiàn)WebSocket協(xié)議客戶(hù)端和服務(wù)器websocket sharp組件實(shí)例解析
這篇文章主要介紹了C#實(shí)現(xiàn)WebSocket協(xié)議客戶(hù)端和服務(wù)器websocket sharp組件實(shí)例解析,包括websocket sharp組件的概念及使用方法,需要的朋友可以參考下2017-04-04
C# 將字節(jié)流轉(zhuǎn)換為圖片的實(shí)例方法
C# 將字節(jié)流轉(zhuǎn)換為圖片的實(shí)例方法,需要的朋友可以參考一下2013-03-03
C#開(kāi)發(fā)微信門(mén)戶(hù)及應(yīng)用(5) 用戶(hù)分組信息管理
這篇文章主要為大家詳細(xì)介紹了C#開(kāi)發(fā)微信門(mén)戶(hù)及應(yīng)用第五篇,用戶(hù)分組信息管理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06

