1. 程式人生 > >TCPListener和TCPClient之間的通信代碼

TCPListener和TCPClient之間的通信代碼

方式 基於 通信 client ogr net odi ask 建立

《服務端》

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading.Tasks;

namespace TCPListener_服務端
{
class Program
{
static void Main(string[] args)
{
//1.創建Socket對象並綁定IP和端口號
TcpListener listener = new TcpListener(IPAddress.Parse("211.148.100.178"), 7788); //這個TcpListener是將Socket創建對象的方式封裝起來存儲在這個類中
//2.開始監聽
listener.Start(100);
//3.等待客戶端連接過來
TcpClient client = listener.AcceptTcpClient();
//4.取得客戶端發送過來的數據
NetworkStream stream = client.GetStream(); //用於接受和發送數據,得到一個網絡流,通過這個網絡流來接受和發送數據
//5.讀取接收到的數據
byte[] data = new byte[1024]; //5.2.創建一個容器用於接受數據並傳入到第一步的第一個位置的參數
//8.將我們需要讀數據和輸出數據的代碼放入一個死循環中去
while (true)
{
int length = stream.Read(data, 0, 1024); //5.1.建立讀數據,需要傳入三個參數和一個返回值。容器、從哪個位置開始、讀取的最大數據、返回值為實際讀取的參數
//6.輸出接收到的這個數據
string message = Encoding.UTF8.GetString(data, 0, length); //1.先將接收到的數據轉化可輸出的字符串類型
Console.WriteLine("收到消息:" + message); //2.輸出收到的信息
}

//7.輸出完數據以後我們需要釋放這些數據
stream.Close(); //1.先釋放流的數據
client.Close(); //2.再釋放客戶端的連接數據
listener.Stop(); //3.關閉監聽
Console.ReadKey();
}
}
}

《客戶端》

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;

namespace TCPClient_客戶端
{
class Program
{
static void Main(string[] args)
{
//1.創建Socket對象並且綁定IP和端口號
TcpClient client = new TcpClient("211.148.100.178", 7788);

//2.創建網絡流和服務端形成交換
NetworkStream stream = client.GetStream();

//5.將3步驟寫入一個死循環中可以讓用戶重復輸入需要的信息
while (true)
{
//3.然後寫入需要交換的數據
string message = Console.ReadLine(); //2.這裏是接受用戶在客戶端中輸入的一段字符串
byte[] data = Encoding.UTF8.GetBytes(message); //3.這個方法就是講輸入的字符串轉化到能夠寫入的byte類型
stream.Write(data, 0, data.Length); //1.這裏是寫入需要傳遞給服務端的數據,第一個參數是傳入的字符數組,第二個是從哪個開始的偏移量,第三個是寫入的數據大小長度
}

//4.關閉流
stream.Close();
client.Close();
Console.ReadKey();
}
}
}

他們都是基於NetworkStream類然後通過stream流通信然後 通過read和write方法來讀和取數據

TCPListener和TCPClient之間的通信代碼