added samples
[windows-sources.git] / sdk / samples / FrameworkSamples / NCL / AsyncSocketServer / asyncsocketclient / program.cs
blobeb672afc423c15d8dfdcc170c696111d15499cdd
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4 using System.Net;
5 using System.Net.Sockets;
6 using System.Threading;
8 //Implements a sample socket client to connect to the server implmented in the AsyncSocketServer project
9 //Usage: AsyncSocketClient.exe <destination IP address> <destination port number>
11 //Destination IP address: The IP Address of the server to connect to
12 //Destination Port Number: The port number to connect to
14 namespace AsyncSocketClient
16 class Program
18 static ManualResetEvent clientDone = new ManualResetEvent(false);
20 static void Main(string[] args)
22 IPAddress destinationAddr = null; // IP Address of server to connect to
23 int destinationPort = 0; // Port number of server
24 SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
27 if (args.Length != 2)
29 Console.WriteLine("Usage: AsyncSocketClient.exe <destination IP address> <destination port number>");
31 try
33 destinationAddr = IPAddress.Parse(args[0]);
34 destinationPort = int.Parse(args[1]);
35 if (destinationPort <= 0){
36 throw new ArgumentException("Destination port number provided cannot be less than or equal to 0");
39 catch (Exception e)
41 Console.WriteLine(e.Message);
42 Console.WriteLine("Usage: AsyncSocketClient.exe <destination IP address> <destination port number>");
45 // Create a socket and connect to the server
46 Socket sock = new Socket(destinationAddr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
47 socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(SocketEventArg_Completed);
48 socketEventArg.RemoteEndPoint = new IPEndPoint(destinationAddr, destinationPort);
49 socketEventArg.UserToken = sock;
50 sock.ConnectAsync(socketEventArg);
51 clientDone.WaitOne();
54 /// <summary>
55 /// A single callback is used for all socket operations. This method forwards execution on to the correct handler
56 /// based on the type of completed operation
57 /// </summary>
58 static void SocketEventArg_Completed(object sender, SocketAsyncEventArgs e)
60 switch (e.LastOperation)
62 case SocketAsyncOperation.Connect:
63 ProcessConnect(e);
64 break;
65 case SocketAsyncOperation.Receive:
66 ProcessReceive(e);
67 break;
68 case SocketAsyncOperation.Send:
69 ProcessSend(e);
70 break;
71 default:
72 throw new Exception("Invalid operation completed");
76 /// <summary>
77 /// Called when a ConnectAsync operation completes
78 /// </summary>
79 private static void ProcessConnect(SocketAsyncEventArgs e)
81 if (e.SocketError == SocketError.Success)
83 Console.WriteLine("Successfully connected to the server");
85 // Send 'Hello World' to the server
86 byte[] buffer = Encoding.UTF8.GetBytes("Hello World");
87 e.SetBuffer(buffer, 0, buffer.Length);
88 Socket sock = e.UserToken as Socket;
89 bool willRaiseEvent = sock.SendAsync(e);
90 if (!willRaiseEvent)
92 ProcessSend(e);
95 else
97 throw new SocketException((int)e.SocketError);
101 /// <summary>
102 /// Called when a ReceiveAsync operation completes
103 /// </summary>
104 private static void ProcessReceive(SocketAsyncEventArgs e)
106 if (e.SocketError == SocketError.Success)
108 Console.WriteLine("Received from server: {0}", Encoding.UTF8.GetString(e.Buffer, 0, e.BytesTransferred));
110 // Data has now been sent and received from the server. Disconnect from the server
111 Socket sock = e.UserToken as Socket;
112 sock.Shutdown(SocketShutdown.Send);
113 sock.Close();
114 clientDone.Set();
116 else
118 throw new SocketException((int)e.SocketError);
123 /// <summary>
124 /// Called when a SendAsync operation completes
125 /// </summary>
126 private static void ProcessSend(SocketAsyncEventArgs e)
128 if (e.SocketError == SocketError.Success)
130 Console.WriteLine("Sent 'Hello World' to the server");
132 //Read data sent from the server
133 Socket sock = e.UserToken as Socket;
134 bool willRaiseEvent = sock.ReceiveAsync(e);
135 if (!willRaiseEvent)
137 ProcessReceive(e);
140 else
142 throw new SocketException((int)e.SocketError);