1.TcpClient
usingSystem;usingSystem.Text;usingSystem.Net.Sockets;namespacetcpclient{classTcpClient {Static voidMain (string[] args) { Try { //establish a client socketTcpClient tcpclnt =NewTcpClient (); Console.WriteLine ("connecting to server ..."); //connecting to a serverTcpclnt. Connect ("127.0.0.1",8081); //get the flow of the clientNetworkStream stm =tcpclnt. GetStream (); while(true) {Console.Write ("The client says:"); stringstr = Console.ReadLine ();//Enter what you say//Send StringSystem.Text.UTF8Encoding UTF8 =NewUTF8Encoding ();//can handle Chinese byte[] ba =UTF8. GetBytes (str); Stm. Write (BA,0, Ba. Length); //receive information returned from the server byte[] BB =New byte[2048]; intK = stm. Read (BB,0, -); //output The information returned by the server sideConsole.WriteLine ("server says:"+ UTF8. GetString (BB,0, K)); } tcpclnt. Close (); } Catch(Exception e) {Console.WriteLine ("error ..."+e.stacktrace); } } }}
2.TcpListener
usingSystem;usingSystem.Text;usingSystem.Net.Sockets;usingSystem.Net;namespacetcpchater{classTCPServer {Static voidMain (string[] args) { Try { //Initialize the listener, port is 8001TcpListener myList =NewTcpListener (Ipaddress.parse ("127.0.0.1"),8081); //start listening on server portMylist.start (); Console.WriteLine ("start server side, Port service ..."); Console.WriteLine ("The local node is:"+ Mylist.localendpoint);//The Localendpoint property identifies the local network interface and port number that is being used to listen for incoming client connection requestsConsole.WriteLine ("waiting for client to connect ..."); //waiting to process an Access connection requestSocket s =Mylist.acceptsocket (); //the newly established connection is represented by the socket sConsole.WriteLine ("client connections from"+ S.remoteendpoint +"is online."); while(true) {System.Text.UTF8Encoding UTF8=NewUTF8Encoding ();//can handle Chinese//Receive customer Information byte[] B =New byte[2048]; intK =s.receive (b); Console.Write ("The client says:"+ UTF8. GetString (b,0, K)); Console.WriteLine (); Console.Write ("server-side says:"); //handling client requests, responding to clients stringstr =Console.ReadLine (); S.send (UTF8. GetBytes (str)); } //release resources, end monitoringS.close (); Mylist.stop (); } Catch(Exception e) {Console.WriteLine ("error ..."+e.stacktrace); } } }}
TcpListener, TcpClient