使用TcpClient的例程
阿新 • • 發佈:2018-05-28
sci while IE his hello program 打印 In read
例子1:
///假定一切工作正常
///連接後發送一次消息,然後不停接受消息並且打印
主要API說明
TcpClient client=new TcpClient();
client.Connect("127.0.0.1",8888);
NetworkStream stream=client.GetStream();
發送:
stream.Write(outBound, 0, outBound.Length);
接受:在另外一個線程,不停的
stream.Read(recvData, 0, bufSize);
class Program { byte[] recvData = newbyte[1024 * 10]; TcpClient client = new TcpClient(); NetworkStream stream = null; void doWork() { client.Connect("127.0.0.1", 8888); stream = client.GetStream(); Thread th = new Thread(recv); th.Start(); byte[] outBound = Encoding.ASCII.GetBytes("Hello,this is one client\r\n"); stream.Write(outBound, 0, outBound.Length); stream.Flush(); } static void Main(string[] args) { Program p = new Program(); p.doWork(); } public void recv() { while(true) { int bufSize = client.ReceiveBufferSize; int count=stream.Read(recvData, 0, bufSize); string str = Encoding.ASCII.GetString(recvData, 0, count); Console.WriteLine(str); } } }
使用TcpClient的例程