C#中使用TCP通信
TCP通信需要通信雙方都在線,所以需要先啟動服務端進行監聽,客戶端才能獲得連接,服務端代碼:
static void Main(string[] args) { TcpClient client = null; NetworkStream stream = null; byte[] buffer = null; string receiveString = null; IPAddress localIP = IPAddress.Parse("127.0.0.1"); int localPort = 11000; TcpListener listener = new TcpListener(localIP, localPort);//用本地IP和端口實例化Listener listener.Start();//開始監聽 while (true) { client = listener.AcceptTcpClient();//接受一個Client buffer = new byte[client.ReceiveBufferSize]; stream = client.GetStream();//獲取網絡流 stream.Read(buffer, 0, buffer.Length);//讀取網絡流中的數據 stream.Close();//關閉流 client.Close();//關閉Client receiveString = Encoding.Default.GetString(buffer).Trim('/0');//轉換成字符串 Console.WriteLine(receiveString); } }
只有服務端開啟監聽后,客戶端才能正確連接,所以服務端要一直開啟監聽,客戶端每次發送數據,都要首先與服務端建立連接,連接建立完成后才進行數據發送。客戶端代碼:
static void Main(string[] args) { string sendString = null;//要發送的字符串 byte[] sendData = null;//要發送的字節數組 TcpClient client = null;//TcpClient實例 NetworkStream stream = null;//網絡流 IPAddress remoteIP = IPAddress.Parse("127.0.0.1");//遠程主機IP int remotePort = 11000;//遠程主機端口 while (true)//死循環 { sendString = Console.ReadLine();//獲取要發送的字符串 sendData = Encoding.Default.GetBytes(sendString);//獲取要發送的字節數組 client = new TcpClient();//實例化TcpClient try { client.Connect(remoteIP, remotePort);//連接遠程主機 } catch (System.Exception ex) { Console.WriteLine("連接超時,服務器沒有響應!");//連接失敗 Console.ReadKey(); return; } stream = client.GetStream();//獲取網絡流 stream.Write(sendData, 0, sendData.Length);//將數據寫入網絡流 stream.Close();//關閉網絡流 client.Close();//關閉客戶端 } }
C#中使用UDP通信
UDP通信是無連接通信,客戶端在發送數據前無需與服務器端建立連接,即使服務器端不在線也可以發送,但是不能保證服務器端可以收到數據。
服務器端代碼:
static void Main(string[] args) { UdpClient client = null; string receiveString = null; byte[] receiveData = null; //實例化一個遠程端點,IP和端口可以隨意指定,等調用client.Receive(ref remotePoint)時會將該端點改成真正發送端端點 IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0); while (true) { client = new UdpClient(11000); receiveData = client.Receive(ref remotePoint);//接收數據 receiveString = Encoding.Default.GetString(receiveData); Console.WriteLine(receiveString); client.Close();//關閉連接 } }
客戶端代碼:
static void Main(string[] args) { string sendString = null;//要發送的字符串 byte[] sendData = null;//要發送的字節數組 UdpClient client = null; IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); int remotePort = 11000; IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//實例化一個遠程端點 while (true) { sendString = Console.ReadLine(); sendData = Encoding.Default.GetBytes(sendString); client = new UdpClient(); client.Send(sendData, sendData.Length, remotePoint);//將數據發送到遠程端點 client.Close();//關閉連接 } }
新聞熱點
疑難解答