例子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 = new byte[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);}}}
例子2:
使用异步,连接异步,发送异步,接受异步
关键API
注意这三者异步回调 委托类型
以下例子会提示连接失败的情况,连接后,接受到消息就打印。
class Program{byte[] recvData = new byte[1024 * 10];TcpClient client = new TcpClient();NetworkStream stream = null;void doWork(){Console.WriteLine("preparing to connect in main thread " + Thread.CurrentThread.ManagedThreadId);client.BeginConnect("127.0.0.1", 8888,ConnectCallBack, client);}static void Main(string[] args){Program p = new Program();p.doWork();Console.Read();}private void ConnectCallBack(IAsyncResult result){Console.WriteLine("well, i am in the connect thread..." + Thread.CurrentThread.ManagedThreadId);TcpClient client = result.AsyncState as TcpClient;try{client.EndConnect(result);}catch (Exception ex){Console.WriteLine("well, seems an error occured...");Console.WriteLine("which is " + ex.ToString());return;}Console.WriteLine("Hooray, it worked.");client.Client.BeginReceive(recvData, 0, recvData.Length,SocketFlags.None, RecvCallBack, client);}public void RecvCallBack(IAsyncResult result){Console.WriteLine("here in recv callback thread.." + Thread.CurrentThread.ManagedThreadId);int count = -1;try{count = client.Client.EndReceive(result);}catch (Exception ex){Console.WriteLine("远程计算机关闭");return;}//an recv is done,display it and continue..string msg = Encoding.ASCII.GetString(recvData, 0, count);Console.WriteLine("your recv this time is:");Console.WriteLine(msg);client.Client.BeginReceive(recvData, 0, recvData.Length, SocketFlags.None, RecvCallBack, client);}}