示例#1
1
 public static void Main()
 {
     using (Socket clientSocket = new Socket(AddressFamily.InterNetwork,
                                             SocketType.Stream,
                                             ProtocolType.Tcp))
     {
         // Addressing
         IPAddress ipAddress = IPAddress.Parse(dottedServerIPAddress);
         IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, port);
         // Connecting
         Debug.Print("Connecting to server " + serverEndPoint + ".");
         clientSocket.Connect(serverEndPoint);
         Debug.Print("Connected to server.");
         using (SslStream sslStream = new SslStream(clientSocket))
         {
             X509Certificate rootCA =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
             X509Certificate clientCert =
                      new X509Certificate(Resources.GetBytes(Resources.BinaryResources.MyRootCA));
             sslStream.AuthenticateAsClient("MyServerName", // Hostname needs to match CN of server cert
                                            clientCert, // Authenticate client
                                            new X509Certificate[] { rootCA }, // CA certs for verification
                                            SslVerification.CertificateRequired, // Verify server
                                            SslProtocols.Default // Protocols that may be required
                                            );
             // Sending
             byte[] messageBytes = Encoding.UTF8.GetBytes("Hello World!");
             sslStream.Write(messageBytes, 0, messageBytes.Length);
         }
     }// the socket will be closed here
 }
        public MFTestResults RunServer()
        {
            MFTestResults testResult = MFTestResults.Fail;

            SslStream sslStream = null;
            try
            {
                IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

                sslServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                //sslServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
                sslServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });

                
                sslServer.Bind(localEndPoint);

                sslServer.Listen(1);

                // Buffer for reading data
                Byte[] bytes = new Byte[2048];
                String data = "";

                // Start Listening for a connection.
                Log.Comment("Waiting for a connection... on IPAddress: " + localEndPoint.Address.ToString() + " Port: " +localEndPoint.Port.ToString());

                // Perform a blocking call to accept requests.
                // block in listening mode until the desktop app connects.  Then we know we can continue.
                Socket client = sslServer.Accept();

                client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });
                //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 30000);
                //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 30000);

                Log.Comment("Connected!");

                // Get a stream object for reading and writing
                sslStream = new SslStream(client);

                sslStream.AuthenticateAsServer(certificate, ca, clientCertificateRequired, enabledSslProtocols);

                int i = -1;
                do
                {
                    // Loop to receive all the data sent by the client.
                    i = sslStream.Read(bytes, 0, bytes.Length);

                    // Translate data bytes to a string.
                    // The encoding used is application specific.
                    string newStr = new string(System.Text.Encoding.UTF8.GetChars(bytes), 0, i);
                    Log.Comment("Received: " + newStr);

                    data += newStr;

                    if (data.IndexOf(SslClient.TERMINATOR) != -1)
                        break;
                } while (i != 0);

                // Send back a response.
                sslStream.Write(bytes, 0, i);
                Log.Comment("Sent:     " + data);

                Thread.Sleep(200);
                testResult = MFTestResults.Pass;
            }
            catch (SocketException e)
            {
                if (expectedException)
                    testResult = MFTestResults.Pass;

                Log.Comment("SocketException in StartServer(): " + e.ToString());
                Log.Comment("ErrorCode: " + e.ErrorCode.ToString());
            }
            catch (Exception e)
            {
                if (expectedException)
                    testResult = MFTestResults.Pass;

                Log.Comment("Exception in StartServer(): " + e.ToString());
            }
            finally
            {
                if (sslServer != null)
                {
                    sslServer.Close();
                }
                if (sslStream != null)
                {
                    sslStream.Dispose();
                }
            }

            return testResult;
        }
示例#3
0
        /// <summary>
        /// Processes client socket requests.  Sends the message received back to the client.
        /// </summary>
        internal void ProcessClient()
        {
            // Application blocks while waiting for an incoming connection.
            while (true)
            {
                try
                {
                    Debug.Print("Waiting for a client to connect...");
                    Socket clientSocket = serverSocket.Accept();

                    Debug.Print("Socket Connected");

                    // A client has connected. Create the 
                    // SslStream using the client's network stream.
                    sslServer = new SslStream(clientSocket);
                    // Authenticate the server but don't require the client to authenticate.

                    sslServer.AuthenticateAsServer(cert, ca, verify, sslProtocols);
                    //Display the properties and settings for the authenticated stream.
                    //DisplaySecurityLevel(sslStream);
                    //DisplaySecurityServices(sslStream);
                    //DisplayCertificateInformation(sslStream);
                    //DisplayStreamProperties(sslStream);

                    // Read a message from the client.   
                    Debug.Print("Waiting for client message...");
                    messageReceived = ReadMessage(sslServer);
                    Debug.Print("Received: " + messageReceived);

                    // Write a message to the client.
                    Debug.Print("Resending message back to client...");
                    sslServer.Write(Encoding.UTF8.GetBytes(messageReceived), 0, messageReceived.Length);

                    // Do not close the SslStream here.  that is to be handled by the test case.

                }
                catch (Exception ex)
                {
                    Debug.Print("Unhandled exception " + ex.Message);
                }
                if (runOnce)
                    return;
            }
        }
示例#4
0
        public bool RunServer()
        {
            //MFTestResults testResult = MFTestResults.Fail;
            bool result = false;

            SslStream sslStream = null;
            Socket client = null;
            try
            {
                if (sslServer == null)
                {
                    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);

                    sslServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    sslServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, false);
                    sslServer.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });


                    sslServer.Bind(localEndPoint);

                    sslServer.Listen(1);
                }

                // Buffer for reading data
                Byte[] bytes = new Byte[2048];
                String data = "";

                // Start Listening for a connection.
                //Log.Comment("Waiting for a connection... on IPAddress: " + localEndPoint.Address.ToString() + " Port: " +localEndPoint.Port.ToString());

                // Perform a blocking call to accept requests.
                // block in listening mode until the desktop app connects.  Then we know we can continue.
                 client = sslServer.Accept();

                //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new byte[] { 0, 0, 0, 0 });
                //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 5000);
                //client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 5000);

                //Log.Comment("Connected!");

                // Get a stream object for reading and writing
                 sslStream = new SslStream(client);          //SK call of SSL_ServerInit in CLR-Code

                sslStream.AuthenticateAsServer(certificate, ca, clientCertificateRequired, enabledSslProtocols);

                sslStream.ReadTimeout = 5000;
                sslStream.WriteTimeout = 5000;
                int i = -1;
                do
                {
                    // Loop to receive all the data sent by the client.
                    try
                    {
                        i = sslStream.Read(bytes, 0, bytes.Length);
                    }
                    catch (Exception)
                    {
                        
                        //throw;
                    }
                   

                    // Translate data bytes to a string.
                    // The encoding used is application specific.
                    string newStr = new string(System.Text.Encoding.UTF8.GetChars(bytes), 0, i);
                    //Log.Comment("Received: " + newStr);

                    data += newStr;

                    if (data.IndexOf(SslClient.TERMINATOR) != -1)
                        break;
                } while (i != 0);

                // Send back a response.
                //sslStream.Write(bytes, 0, i);
                // Return a static HTML document to the client.
                String s =
                    "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\n\r\n<html><head><title>.NET Micro Framework Web Server</title></head>" +
                   "<body>";
                sslStream.Write(Encoding.UTF8.GetBytes(s), 0, Encoding.UTF8.GetBytes(s).Length);

                for(int j = 0; j < 1000; j++)
                {
                    s = "<p><bold><a href=\"http://www.microsoft.com/netmf/\">Learn more about the .NET Micro Framework by clicking here</a></bold></p>";
                    sslStream.Write(Encoding.UTF8.GetBytes(s), 0, Encoding.UTF8.GetBytes(s).Length);
                }

                s = "</body></html>";
                sslStream.Write(Encoding.UTF8.GetBytes(s), 0, Encoding.UTF8.GetBytes(s).Length);
                //Log.Comment("Sent:     " + data);

                Thread.Sleep(200);
                result = true;
            }
            catch (SocketException e)
            {
                if (expectedException)
                    result = true;

                //Log.Comment("SocketException in StartServer(): " + e.ToString());
                //Log.Comment("ErrorCode: " + e.ErrorCode.ToString());
            }
            catch (Exception e)
            {
                if (expectedException)
                    result = true;

                //Log.Comment("Exception in StartServer(): " + e.ToString());
            }
            finally
            {
 
                if (sslStream != null)
                {
                    sslStream.Close();
                    sslStream.Dispose();
                    //sslStream.Flush();
                   
                }
                if (sslServer != null)
                {
                  // sslServer.Close();
                }

               
            }
     return result;
        }
示例#5
0
        public MFTestResults RunClient()
        {
             MFTestResults testResult = MFTestResults .Pass;
            try
            {
                if (ipAddress == null)
                    Debug.Print("IpAddress must be initialized before calling RunClient()");
                else
                    serverEp = new IPEndPoint(ipAddress, port);

                // Create a TCP/IP client socket.
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                clientSocket.Connect(serverEp);

                // Create an SSL stream that will close the client's stream.
                sslClient = new SslStream(clientSocket);

                Log.Comment("Calling AuthenticateAsClient()");
                // The server name must match the name on the server certificate.
                sslClient.AuthenticateAsClient(targetHost, cert, ca, verify, sslProtocols);

                // Send hello message to the server. 
                byte[] message = Encoding.UTF8.GetBytes(messageSent);
                sslClient.Write(message, 0, message.Length);
                Log.Comment("Sent:     " + messageSent);

                // Read message from the server.
                messageReceived = ReadMessage(sslClient);
                Log.Comment("Received: " + messageReceived);

                if (messageSent != messageReceived)
                    testResult = MFTestResults.Fail;

            }
            catch (SocketException e)
            {
                if (!expectedException)
                    testResult = MFTestResults.Fail;
                Log.Comment("ErrorCode: " + e.ErrorCode);
                Log.Comment("An exception occurred: " + e.Message);
            }
            catch (Exception e)
            {
                if (!expectedException)
                    testResult = MFTestResults.Fail;
                Log.Comment("An exception occurred: " + e.Message);
            }
            finally
            {
                if (sslClient != null)
                {
                    Thread.Sleep(50);
                    sslClient.Dispose();
                    sslClient = null;
                }
                if (clientSocket != null)
                {
                    clientSocket.Close();
                    clientSocket = null;
                }
            }
            return testResult;
        }
示例#6
0
        public void RunClient()
        {
            // Create a TCP/IP client socket.
            clientSocket = new Socket(AddressFamily.InterNetwork, clientSocketType, clientProtocolType);

            clientSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));

            while (true)
            {
                try
                {
                    // Connect to the server
                    clientSocket.Connect(serverEp);
                    break;
                }
                catch (SocketException)
                {
                    // Server down, try again
                    Thread.Sleep(1000);
                }
            }
            Log.Comment("Client connected.");
           
            // Create an SSL stream that will close the client's stream.
            sslClient = new SslStream(clientSocket);

            // The server name must match the name on the server certificate.
            sslClient.AuthenticateAsClient(targetHost, cert, ca, verify, sslProtocols);

            // Send hello message to the server. 
            Log.Comment("Sending message to Server: " + messageSent);
            byte[] message = Encoding.UTF8.GetBytes(messageSent);
            sslClient.Write(message, 0, message.Length);

            Log.Comment("do we need to flush? after a write?");
            sslClient.Flush();

            // Read message from the server.
            messageReceived = ReadMessage(sslClient);
            Log.Comment("Server says:" + messageReceived);
                
            // Do not close the clientSslStream.  That is handled by the test case.
        }