使用.NET访问Internet(5)

同步客户端套接字示例

下面的示例程序创建一个连接到服务器的客户端。该客户端是用同步套接字生成的,因此挂起客户端应用程序的执行,直到服务器返回响应为止。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。

 [C#]


using System;


using System.Net;


using System.Net.Sockets;


using System.Text;


 


public class SynchronousSocketClient {


 


  public static void StartClient() {


    // Data buffer for incoming data.


    byte[] bytes = new byte[1024];


 


    // Connect to a remote device.


    try {


      // Establish the remote endpoint for the socket.


      //    The name of the


      //   remote device is "host.contoso.com".


      IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");


      IPAddress ipAddress = ipHostInfo.AddressList[0];


      IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);


 


      // Create a TCP/IP  socket.


      Socket sender = new Socket(AddressFamily.InterNetwork, 


        SocketType.Stream, ProtocolType.Tcp );


 


      // Connect the socket to the remote endpoint. Catch any errors.


      try {


        sender.Connect(remoteEP);


 


        Console.WriteLine("Socket connected to {0}",


          sender.RemoteEndPoint.ToString());


 


        // Encode the data string into a byte array.


        byte[] msg = Encoding.ASCII.GetBytes("This is a test
  1<eof>");
  2    
  3    
  4     
  5    
  6    
  7            // Send the data through the  socket.
  8    
  9    
 10            int bytesSent = sender.Send(msg);
 11    
 12    
 13     
 14    
 15    
 16            // Receive the response from the remote device.
 17    
 18    
 19            int bytesRec = sender.Receive(bytes);
 20    
 21    
 22            Console.WriteLine("Echoed test = {0}",
 23    
 24    
 25              Encoding.ASCII.GetString(bytes,0,bytesRec));
 26    
 27    
 28     
 29    
 30    
 31            // Release the socket.
 32    
 33    
 34            sender.Shutdown(SocketShutdown.Both);
 35    
 36    
 37            sender.Close();
 38    
 39    
 40            
 41    
 42    
 43          } catch (ArgumentNullException ane) {
 44    
 45    
 46            Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
 47    
 48    
 49          } catch (SocketException se) {
 50    
 51    
 52            Console.WriteLine("SocketException : {0}",se.ToString());
 53    
 54    
 55          } catch (Exception e) {
 56    
 57    
 58            Console.WriteLine("Unexpected exception : {0}", e.ToString());
 59    
 60    
 61          }
 62    
 63    
 64     
 65    
 66    
 67        } catch (Exception e) {
 68    
 69    
 70          Console.WriteLine( e.ToString());
 71    
 72    
 73        }
 74    
 75    
 76      }
 77    
 78    
 79      
 80    
 81    
 82      public static int Main(String[] args) {
 83    
 84    
 85        StartClient();
 86    
 87    
 88        return 0;
 89    
 90    
 91      }
 92    
 93    
 94    }
 95
 96###  同步服务器套接字示例 
 97
 98下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用同步套接字生成的,因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串  “<eof>”,以发出表示消息结尾的信号。 
 99    
100    
101     [C#]
102    
103    
104    using System;
105    
106    
107    using System.Net;
108    
109    
110    using System.Net.Sockets;
111    
112    
113    using System.Text;
114    
115    
116     
117    
118    
119    public class SynchronousSocketListener {
120    
121    
122      
123    
124    
125      // Incoming data from the client.
126    
127    
128      public static string data = null;
129    
130    
131     
132    
133    
134      public static void StartListening() {
135    
136    
137        // Data buffer for incoming data.
138    
139    
140        byte[] bytes = new Byte[1024];
141    
142    
143     
144    
145    
146        // Establish the local endpoint for the  socket.
147    
148    
149        //  Dns.GetHostName returns the name of the 
150    
151    
152        // host running the application.
153    
154    
155        IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
156    
157    
158        IPAddress ipAddress = ipHostInfo.AddressList[0];
159    
160    
161        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
162    
163    
164     
165    
166    
167        // Create a TCP/IP socket.
168    
169    
170        Socket listener = new Socket(AddressFamily.InterNetwork,
171    
172    
173          SocketType.Stream, ProtocolType.Tcp );
174    
175    
176     
177    
178    
179        // Bind the socket to the local endpoint and 
180    
181    
182        // listen for incoming connections.
183    
184    
185        try {
186    
187    
188          listener.Bind(localEndPoint);
189    
190    
191          listener.Listen(10);
192    
193    
194     
195    
196    
197          // Start listening for connections.
198    
199    
200          while (true) {
201    
202    
203            Console.WriteLine("Waiting for a connection...");
204    
205    
206            // Program is suspended while waiting for an incoming connection.
207    
208    
209            Socket handler = listener.Accept();
210    
211    
212            data = null;
213    
214    
215     
216    
217    
218            // An incoming connection needs to be processed.
219    
220    
221            while (true) {
222    
223    
224              bytes = new byte[1024];
225    
226    
227              int bytesRec = handler.Receive(bytes);
228    
229    
230              data += Encoding.ASCII.GetString(bytes,0,bytesRec);
231    
232    
233              if (data.IndexOf("<eof>") &gt; -1) {
234    
235    
236                break;
237    
238    
239              }
240    
241    
242            }
243    
244    
245     
246    
247    
248            // Show the data on the console.
249    
250    
251            Console.WriteLine( "Text received : {0}", data);
252    
253    
254     
255    
256    
257            // Echo the data back to the client.
258    
259    
260            byte[] msg = Encoding.ASCII.GetBytes(data);
261    
262    
263     
264    
265    
266            handler.Send(msg);
267    
268    
269            handler.Shutdown(SocketShutdown.Both);
270    
271    
272            handler.Close();
273    
274    
275          }
276    
277    
278          
279    
280    
281        } catch (Exception e) {
282    
283    
284          Console.WriteLine(e.ToString());
285    
286    
287        }
288    
289    
290     
291    
292    
293        Console.WriteLine("\nHit enter to continue...");
294    
295    
296        Console.Read();
297    
298    
299        
300    
301    
302      }
303    
304    
305     
306    
307    
308      public static int Main(String[] args) {
309    
310    
311        StartListening();
312    
313    
314        return 0;
315    
316    
317      }
318    
319    
320    }
321
322###  异步客户端套接字示例 
323
324下面的示例程序创建一个连接到服务器的客户端。该客户端是用异步套接字生成的,因此在等待服务器返回响应时不挂起客户端应用程序的执行。该应用程序将字符串发送到服务器,然后在控制台显示该服务器返回的字符串。 
325    
326    
327     [C#]
328    
329    
330    using System;
331    
332    
333    using System.Net;
334    
335    
336    using System.Net.Sockets;
337    
338    
339    using System.Threading;
340    
341    
342    using System.Text;
343    
344    
345     
346    
347    
348    // State object for receiving data from remote device.
349    
350    
351    public class StateObject {
352    
353    
354      public Socket workSocket = null;              // Client socket.
355    
356    
357      public const int BufferSize = 256;            // Size of receive buffer.
358    
359    
360      public byte[] buffer = new byte[BufferSize];  // Receive buffer.
361    
362    
363      public StringBuilder sb = new StringBuilder();// Received data string.
364    
365    
366    }
367    
368    
369     
370    
371    
372    public class AsynchronousClient {
373    
374    
375      // The port number for the remote device.
376    
377    
378      private const int port = 11000;
379    
380    
381     
382    
383    
384      // ManualResetEvent instances signal completion.
385    
386    
387      private static ManualResetEvent connectDone = 
388    
389    
390        new ManualResetEvent(false);
391    
392    
393      private static ManualResetEvent sendDone = 
394    
395    
396        new ManualResetEvent(false);
397    
398    
399      private static ManualResetEvent receiveDone = 
400    
401    
402        new ManualResetEvent(false);
403    
404    
405     
406    
407    
408      // The response from the remote device.
409    
410    
411      private static String response = String.Empty;
412    
413    
414     
415    
416    
417      private static void StartClient() {
418    
419    
420        // Connect to a remote device.
421    
422    
423        try {
424    
425    
426          // Establish the remote endpoint for the socket.
427    
428    
429          // "host.contoso.com" is the name of the
430    
431    
432          // remote device.
433    
434    
435          IPHostEntry ipHostInfo = Dns.Resolve("host.contoso.com");
436    
437    
438          IPAddress ipAddress = ipHostInfo.AddressList[0];
439    
440    
441          IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
442    
443    
444     
445    
446    
447          //  Create a TCP/IP  socket.
448    
449    
450          Socket client = new Socket(AddressFamily.InterNetwork,
451    
452    
453            SocketType.Stream, ProtocolType.Tcp);
454    
455    
456     
457    
458    
459          // Connect to the remote endpoint.
460    
461    
462          client.BeginConnect( remoteEP, 
463    
464    
465            new AsyncCallback(ConnectCallback), client);
466    
467    
468          connectDone.WaitOne();
469    
470    
471     
472    
473    
474          // Send test data to the remote device.
475    
476    
477          Send(client,"This is a test<eof>");
478    
479    
480          sendDone.WaitOne();
481    
482    
483     
484    
485    
486          // Receive the response from the remote device.
487    
488    
489          Receive(client);
490    
491    
492          receiveDone.WaitOne();
493    
494    
495     
496    
497    
498          // Write the response to the console.
499    
500    
501          Console.WriteLine("Response received : {0}", response);
502    
503    
504     
505    
506    
507          // Release the socket.
508    
509    
510          client.Shutdown(SocketShutdown.Both);
511    
512    
513          client.Close();
514    
515    
516          
517    
518    
519        } catch (Exception e) {
520    
521    
522          Console.WriteLine(e.ToString());
523    
524    
525        }
526    
527    
528      }
529    
530    
531     
532    
533    
534      private static void ConnectCallback(IAsyncResult ar) {
535    
536    
537        try {
538    
539    
540          // Retrieve the socket from the state object.
541    
542    
543          Socket client = (Socket) ar.AsyncState;
544    
545    
546     
547    
548    
549          // Complete the connection.
550    
551    
552          client.EndConnect(ar);
553    
554    
555     
556    
557    
558          Console.WriteLine("Socket connected to {0}",
559    
560    
561            client.RemoteEndPoint.ToString());
562    
563    
564     
565    
566    
567          // Signal that the connection has been made.
568    
569    
570          connectDone.Set();
571    
572    
573        } catch (Exception e) {
574    
575    
576          Console.WriteLine(e.ToString());
577    
578    
579        }
580    
581    
582      }
583    
584    
585     
586    
587    
588      private static void Receive(Socket client) {
589    
590    
591        try {
592    
593    
594          // Create the state object.
595    
596    
597          StateObject state = new StateObject();
598    
599    
600          state.workSocket = client;
601    
602    
603     
604    
605    
606          // Begin receiving the data from the remote device.
607    
608    
609          client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
610    
611    
612            new AsyncCallback(ReceiveCallback), state);
613    
614    
615        } catch (Exception e) {
616    
617    
618          Console.WriteLine(e.ToString());
619    
620    
621        }
622    
623    
624      }
625    
626    
627     
628    
629    
630      private static void ReceiveCallback( IAsyncResult ar ) {
631    
632    
633        try {
634    
635    
636          // Retrieve the state object and the client socket 
637    
638    
639          // from the async state object.
640    
641    
642          StateObject state = (StateObject) ar.AsyncState;
643    
644    
645          Socket client = state.workSocket;
646    
647    
648     
649    
650    
651          // Read data from the remote device.
652    
653    
654          int bytesRead = client.EndReceive(ar);
655    
656    
657     
658    
659    
660          if (bytesRead &gt; 0) {
661    
662    
663            // There might be more data, so store the data received so far.
664    
665    
666          state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
667    
668    
669     
670    
671    
672            //  Get the rest of the data.
673    
674    
675            client.BeginReceive(state.buffer,0,StateObject.BufferSize,0,
676    
677    
678              new AsyncCallback(ReceiveCallback), state);
679    
680    
681          } else {
682    
683    
684            // All the data has arrived; put it in response.
685    
686    
687            if (state.sb.Length &gt; 1) {
688    
689    
690              response = state.sb.ToString();
691    
692    
693            }
694    
695    
696            // Signal that all bytes have been received.
697    
698    
699            receiveDone.Set();
700    
701    
702          }
703    
704    
705        } catch (Exception e) {
706    
707    
708          Console.WriteLine(e.ToString());
709    
710    
711        }
712    
713    
714      }
715    
716    
717     
718    
719    
720      private static void Send(Socket client, String data) {
721    
722    
723        // Convert the string data to byte data using ASCII encoding.
724    
725    
726        byte[] byteData = Encoding.ASCII.GetBytes(data);
727    
728    
729     
730    
731    
732        // Begin sending the data to the remote device.
733    
734    
735        client.BeginSend(byteData, 0, byteData.Length, 0,
736    
737    
738          new AsyncCallback(SendCallback), client);
739    
740    
741      }
742    
743    
744     
745    
746    
747      private static void SendCallback(IAsyncResult ar) {
748    
749    
750        try {
751    
752    
753          // Retrieve the socket from the state object.
754    
755    
756          Socket client = (Socket) ar.AsyncState;
757    
758    
759     
760    
761    
762          // Complete sending the data to the remote device.
763    
764    
765          int bytesSent = client.EndSend(ar);
766    
767    
768          Console.WriteLine("Sent {0} bytes to server.", bytesSent);
769    
770    
771     
772    
773    
774          // Signal that all bytes have been sent.
775    
776    
777          sendDone.Set();
778    
779    
780        } catch (Exception e) {
781    
782    
783          Console.WriteLine(e.ToString());
784    
785    
786        }
787    
788    
789      }
790    
791    
792      
793    
794    
795      public static int Main(String[] args) {
796    
797    
798        StartClient();
799    
800    
801        return 0;
802    
803    
804      }
805    
806    
807    }
808
809###  异步服务器套接字示例 
810
811下面的示例程序创建一个接收来自客户端的连接请求的服务器。该服务器是用异步套接字生成的,因此在等待来自客户端的连接时不挂起服务器应用程序的执行。该应用程序接收来自客户端的字符串,在控制台显示该字符串,然后将该字符串回显到客户端。来自客户端的字符串必须包含字符串  “<eof>”,以发出表示消息结尾的信号。 
812    
813    
814     [C#]
815    
816    
817    using System;
818    
819    
820    using System.Net;
821    
822    
823    using System.Net.Sockets;
824    
825    
826    using System.Text;
827    
828    
829    using System.Threading;
830    
831    
832     
833    
834    
835    // State object for reading client data asynchronously
836    
837    
838    public class StateObject {
839    
840    
841       public Socket workSocket = null;       // Client  socket.
842    
843    
844       public const int BufferSize = 1024;       // Size of receive buffer.
845    
846    
847       public byte[] buffer = new byte[BufferSize]; // Receive buffer.
848    
849    
850       public StringBuilder sb = new StringBuilder();  // Received data string.
851    
852    
853    }
854    
855    
856     
857    
858    
859    public class AsynchronousSocketListener {
860    
861    
862       
863    
864    
865       // Incoming data from client.
866    
867    
868       public static string data = null;
869    
870    
871     
872    
873    
874       // Thread signal.
875    
876    
877       public static ManualResetEvent allDone = new ManualResetEvent(false);
878    
879    
880     
881    
882    
883       public AsynchronousSocketListener() {
884    
885    
886       }
887    
888    
889     
890    
891    
892       public static void StartListening() {
893    
894    
895          // Data buffer for incoming data.
896    
897    
898          byte[] bytes = new Byte[1024];
899    
900    
901     
902    
903    
904          // Establish the local endpoint for the  socket.
905    
906    
907          //   The DNS name of the computer
908    
909    
910          //  running the listener is "host.contoso.com".
911    
912    
913          IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
914    
915    
916          IPAddress ipAddress = ipHostInfo.AddressList[0];
917    
918    
919          IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
920    
921    
922     
923    
924    
925          // Create a TCP/IP  socket.
926    
927    
928          Socket listener = new Socket(AddressFamily.InterNetwork,
929    
930    
931             SocketType.Stream, ProtocolType.Tcp );
932    
933    
934     
935    
936    
937          // Bind the  socket to the local endpoint and listen for incoming connections.
938    
939    
940          try {
941    
942    
943             listener.Bind(localEndPoint);
944    
945    
946             listener.Listen(100);
947    
948    
949     
950    
951    
952             while (true) {
953    
954    
955                // Set the event to  nonsignaled state.
956    
957    
958                allDone.Reset();
959    
960    
961     
962    
963    
964                // Start  an asynchronous socket to listen for connections.
965    
966    
967                Console.WriteLine("Waiting for a connection...");
968    
969    
970                listener.BeginAccept( 
971    
972    
973                   new AsyncCallback(AcceptCallback),
974    
975    
976                   listener );
977    
978    
979    &lt;SPAN lang=EN-</eof></eof></eof></eof></eof>
Published At
Categories with Web编程
Tagged with
comments powered by Disqus