標籤:stat buffers ipad linq port client space remote catch
服務端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ceshi1
{
class Program
{
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();//關閉用戶端
}
}
}
}
客戶接收端:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace ceshi
{
class Program
{
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);
}
}
}
}
C#TCP,網路流通訊執行個體