【问题标题】:Using SSL Stream with Asynchronous System.Net.Sockets将 SSL 流与异步 System.Net.Sockets 一起使用
【发布时间】:2012-09-02 08:29:41
【问题描述】:

我的服务器现在使用异步 System.Net.Sockets 运行,但我想使用 SSL 流。我对使用 SSL 很陌生,所以如果有人可以帮助我,这是我的服务器代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;

    public class Wrapper
    {
        public byte[] buffer;
        public Socket _socket;
        public object connector;
    }

    public class WinSocket
    {
        private Dictionary<string, byte> Connections;
        public event Action<Wrapper> AnnounceNewConnection;//Event Handlers
        public event Action<Wrapper> AnnounceDisconnection;
        public event Action<byte[], Wrapper> AnnounceReceive;
        private Socket _socket;
        public int MAX_USER_CONNECTIONS = 2;//Max User Connections

        public WinSocket(ushort port)
        {
            try
            {
                Connections = new Dictionary<string, byte>();
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Bind(new IPEndPoint(IPAddress.Any, port));
                _socket.Listen(500);
                _socket.BeginAccept(AcceptConnections, new Wrapper());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);//write an exception
            }
        }

        private void AcceptConnections(IAsyncResult result)
        {
            try
            {
                Wrapper wr = result.AsyncState as Wrapper;
                wr._socket = _socket.EndAccept(result);
                #region Invisible
                string IP = wr._socket.RemoteEndPoint.ToString().Split(':')[0].ToString();//Get user ip
                if (!Connections.ContainsKey(IP))
                    Connections.Add(IP, 1);
                else
                    if (Connections[IP] <= MAX_USER_CONNECTIONS)//Maximum Connections Per IP
                    {
                        byte connections = Connections[IP];
                        Connections.Remove(IP);//Limit exceeded
                        Connections.Add(IP, (byte)(connections + 1));
                    }
                    else
                    {
                        wr._socket.Disconnect(false);
                        _socket.BeginAccept(AcceptConnections, new Wrapper());
                        return;
                    }
                #endregion
                wr.buffer = new byte[65535];
                wr._socket.BeginReceive(wr.buffer, 0, 65535, SocketFlags.None, ReceiveData, wr);
                AnnounceNewConnection.Invoke(wr);
                _socket.BeginAccept(AcceptConnections, new Wrapper());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);//write an exception
            }
        }

        private void ReceiveData(IAsyncResult result)//Receiving Data
        {
            try
            {
                Wrapper wr = result.AsyncState as Wrapper;
                string IP = wr._socket.RemoteEndPoint.ToString().Split(':')[0].ToString();//Get UIP
                if (Connections.ContainsKey(IP))
                {
                    SocketError error = SocketError.Disconnecting;
                    int size = wr._socket.EndReceive(result, out error);
                    if (error == SocketError.Success && size != 0)
                    {
                        byte[] buffer = new byte[size];
                        Buffer.BlockCopy(wr.buffer, 0, buffer, 0, size);
                        AnnounceReceive.Invoke(buffer, wr);//The delegate
                        if (wr._socket.Connected)//Make sure socket is connected
                            wr._socket.BeginReceive(wr.buffer, 0, 65535, SocketFlags.None, ReceiveData, wr);//Start Receiving Data
                    }
                    else
                    {
                        if (wr._socket.Connected)
                        {
                            wr._socket.Disconnect(true);//Disconnect the client
                        }
                        byte connections = Connections[IP];
                        Connections.Remove(IP);
                        Connections.Add(IP, (byte)(connections - 1));
                        try
                        {
                            AnnounceDisconnection.Invoke(wr);
                        }
                        catch { }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);//write an exception
            }
        }
    }

所以我的问题再次明确是:如何使用 SSL Stream 和上面的代码一样的套接字类

【问题讨论】:

  • 您遇到了什么错误?除了问题中包含的内容之外,您是否尝试过其他任何内容?
  • 我没有收到错误我上面的代码正在运行,但我想在其中使用 SSL 来保护我的连接,我不知道如何

标签: sockets ssl asynchronous stream certificate


【解决方案1】:

Stream 类替换为System.Net.SslStream 类。除上述代码外,调用AuthenticateAsServer,并在WinSocket构造函数中传递服务器SSL证书。

【讨论】:

  • 对不起,但有一个小要求:您能否突出显示需要编辑的部分或编辑我为我提供的代码?因为我对 SSL 完全感到困惑
  • 请帮助我,我正在尝试编辑它,但总是我得到对象引用未设置为对象的实例
猜你喜欢
  • 2016-09-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-16
  • 1970-01-01
  • 2020-07-18
相关资源
最近更新 更多