TCP通訊簡介
TCP(傳輸控制協議,Transmission Control Protocol)是一種面向連線的、可靠的、基於位元組流的傳輸層通訊協議。它確保資料包按順序傳輸,並在必要時進行重傳,以保證資料的完整性和準確性。TCP透過三次握手建立連線,透過四次揮手釋放連線,確保通訊雙方在傳輸資料前已準備好,並在傳輸結束後正確關閉連線。TCP廣泛應用於需要高可靠性的網路應用,如網頁瀏覽、檔案傳輸和電子郵件等。
Demo效果
啟動兩個應用,一個當服務端,一個當客戶端。
開啟服務端:
開啟客戶端:
客戶端向服務端傳送訊息:
服務端向客戶端傳送訊息:
Demo程式碼
啟動服務端:
[RelayCommand]
private async Task StartServer()
{
System.Net.IPAddress Ip = System.Net.IPAddress.Parse(IpAddress);
_tcpServer = new TcpListener(Ip, Port);
_tcpServer.Start();
Message += "Server started. Waiting for a connection...\r\n";
// 接受客戶端連線
_tcpServer_Client = await _tcpServer.AcceptTcpClientAsync();
Message += "客戶端已連線\r\n";
// Handle client communication
_ = HandleClientAsync(_tcpServer_Client);
}
private async Task HandleClientAsync(TcpClient client)
{
var stream = client.GetStream();
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Message+=$"Received from client: {message}\r\n";
// Echo the message back to the client
//var response = Encoding.UTF8.GetBytes($"Echo: {message}");
//await stream.WriteAsync(response, 0, response.Length);
}
Message += "Client disconnected...\r\n";
stream.Close();
}
啟動客戶端:
[RelayCommand]
private async Task StartClient()
{
System.Net.IPAddress Ip = System.Net.IPAddress.Parse(IpAddress);
_tcpClient = new TcpClient();
await _tcpClient.ConnectAsync(Ip, Port);
Message += "Connected to server...\r\n";
_ = HandleServerCommunicationAsync(_tcpClient);
}
private async Task HandleServerCommunicationAsync(TcpClient client)
{
var stream = client.GetStream();
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Message += $"Received from server: {message}\r\n";
}
Message += "Disconnected from server...\r\n";
stream.Close();
}
向服務端發訊息:
[RelayCommand]
private async Task SendMessageToServer()
{
if (_tcpClient == null || !_tcpClient.Connected)
{
Message += "Not connected to server.\r\n";
return;
}
var stream = _tcpClient.GetStream();
var data = Encoding.UTF8.GetBytes(Text);
await stream.WriteAsync(data, 0, data.Length);
Message += $"Sent: {Text}\r\n";
}
向客戶端發訊息:
[RelayCommand]
private async Task SendMessageToClient()
{
if (_tcpServer_Client == null || !_tcpServer_Client.Connected)
{
Message += "Not connected to client.\r\n";
return;
}
var stream = _tcpServer_Client.GetStream();
var data = Encoding.UTF8.GetBytes(Text);
await stream.WriteAsync(data, 0, data.Length);
Message += $"Sent: {Text}\r\n";
}
全部程式碼已上傳至https://github.com/Ming-jiayou/AvaloniaTCP。
希望透過我的點滴分享,能夠讓對Avalonia感興趣的朋友,更快入門。