Inheritance: IDisposable
Example #1
1
 public AesStream(Socket socket, EnhancedStream stream, byte[] key)
     : base(socket)
 {
     BaseStream = stream;
     _enc = new CryptoStream(stream, GenerateAES(key).CreateEncryptor(), CryptoStreamMode.Write);
     _dec = new CryptoStream(stream, GenerateAES(key).CreateDecryptor(), CryptoStreamMode.Read);
 }
Example #2
0
 public ClientConnection(Socket socket)
     : base(socket)
 {
     DisconnectedEvent += ClientConnection_DisconnectedEvent;
     m_LittleEndian = true;
     Logger.Trace("Client {0}: Connected", this);
 }
        public AuthChallenge(Socket conn)
        {
            int soFar = 0;
            byte[] buffer = new byte[MESSAGE_SIZE];

            while (soFar < MESSAGE_SIZE)
            {
                //read the header and challenge phrase
                int rcvd = conn.Receive(buffer, (int)MESSAGE_SIZE - soFar, SocketFlags.None);
                if (rcvd == 0) throw new AuthException("Disconnect during authentication");
                if (soFar == 0 && buffer[0] != PACKET_IDENTIFIER) throw new AuthException("Invalid challenge packet header");

                //skip the first byte
                if (soFar == 0)
                {
                    if (rcvd > 1) _challenge.Append(buffer, 1, rcvd - 1);
                }
                else
                {
                    _challenge.Append(buffer, 0, rcvd);
                }

                soFar += rcvd;
            }
        }
Example #4
0
        public void reConnect()
        {
            serviceSocket.Close();
            serviceSocket = null;
            sendBuffer = new byte[1024];//Send buffer //c# automatic assigesd to 0     

            try
            {
                serviceSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                System.Threading.Thread tt = new System.Threading.Thread(delegate()
                {
                    try
                    {
                        serviceSocket.Connect(ip, port);
                    }
                    catch (Exception ee)
                    {
                        //MessageBox.Show(ee.Message + "\r\n From:" + this);
                    }
                });
                tt.Start();

            }
            catch (Exception e)
            {
                //MessageBox.Show(e.Message + "\r\n From:" + this);
            }
        }
 public ProcessQueue(int _cardNo, Player _user, Socket _userSocket, Player _target)
 {
     cardNo = _cardNo;
     user = _user;
     target = _target;
     userSocket = _userSocket;
 }
Example #6
0
 public AbstractSession(Socket sck)
 {
     this.Actived = false;
     this.Socket = sck;
     this.Handle = sck.Handle.ToInt32();
     this.RemoteEndpoint = sck.RemoteEndPoint.ToString();
 }
        public bool initializeConnection()
        {
            try
            {
                m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

                m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                m_socket.SendTimeout = 5000;
                m_socket.ReceiveTimeout = 5000;

                m_frm.Print("Connecting to " + ECCServerIP + " at port " + ECCServerPort + " ...");
                m_socket.Connect(ECCServerIP, Convert.ToInt32(ECCServerPort));
            }
            catch (Exception ex)
            {
                m_frm.Print("Error!Failed to connect to ECC server!" + ex.Message);
                return false;
            }

            if (!Authenticate())
                return false;

            return true;
        }
Example #8
0
 public static void CheckDualModeReceiveSupport(Socket socket)
 {
     if (!SupportsDualModeIPv4PacketInfo && socket.AddressFamily == AddressFamily.InterNetworkV6 && socket.DualMode)
     {
         throw new PlatformNotSupportedException(SR.net_sockets_dualmode_receivefrom_notsupported);
     }
 }
 public void Dispose()
 {
     Socket.Disconnect(false);
     Socket.Shutdown(SocketShutdown.Both);
     Socket.Close();
     Socket = null;
 }
Example #10
0
 public Client(Socket s)
 {
     clientSocket = s;
     //启动一个线程处理客户端的数据接收
     t = new Thread(ReceiveMessage);
     t.Start();
 }
        // The read socket that creates this object sends a copy of its "parent" accept socket in as a reference
        // We also take in a max buffer size for the data to be read off of the read socket
        public OSUserToken(Socket readSocket, Int32 bufferSize, IEFMagLinkRepository repository)
        {
            _repository = repository;
            ownersocket = readSocket;
            stringbuilder = new StringBuilder(bufferSize);

        }
 public AsyncSocketSession(Socket client, SocketAsyncEventArgsProxy socketAsyncProxy, bool isReset)
     : base(client)
 {
     SocketAsyncProxy = socketAsyncProxy;
     m_OrigOffset = socketAsyncProxy.SocketEventArgs.Offset;
     m_IsReset = isReset;
 }
Example #13
0
 public WorkerProxy(NagCoordinator coordinator, Socket socket)
 {
     Worker = new TCPConnection(socket, false, ProcesLine, null);
     NagCoordinator = coordinator;
     State = ConnectionState.Negotiating;
     Negotiate();
 }
        /// <summary>
        /// 启动监听
        /// </summary>
        /// <param name="config">服务器配置</param>
        /// <returns></returns>
        public override bool Start(IServerConfig config)
        {
            m_ListenSocket = new System.Net.Sockets.Socket(this.Info.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                //关联终结地
                m_ListenSocket.Bind(this.Info.EndPoint);
                //设置监听最大连接数
                m_ListenSocket.Listen(m_ListenBackLog);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

                m_ListenSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);
                //初始化套接字操作
                SocketAsyncEventArgs acceptEventArg = new SocketAsyncEventArgs();
                m_AcceptSAE = acceptEventArg;
                //定义一个连接完成事件
                acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(acceptEventArg_Completed);
                if (!m_ListenSocket.AcceptAsync(acceptEventArg))
                {
                    ProcessAccept(acceptEventArg);
                }
                return true;
            }
            catch (Exception e)
            {
                OnError(e);
                return false;
            }
        }
Example #15
0
 public OnlineUser(Socket socket, String username, String token, String publicKey)
 {
     WorkSocket = socket;
     Username = username;
     this.token = token;
     PublicKey = publicKey;
 }
        public static int DestorySocket(Socket socket)
        {
            int r = -1;
            try
            {
                //if (_socket.Connected)
                //{
                //    _socket.Disconnect(false);

                //}
                if (socket != null)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.DisconnectAsync(null);
                    
                    socket.Close();
                    socket.Dispose();
                    socket = null;
                }
                r = 0;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                r = -1;
            }
            return r;
        }
Example #17
0
        /// <summary>
        /// Checks the connection.
        /// </summary>
        /// <param name="sock">The sock.</param>
        /// <param name="maxIpConnectionCount">The maximum ip connection count.</param>
        /// <param name="antiDDosStatus">if set to <c>true</c> [anti d dos status].</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        internal static bool CheckConnection(Socket sock, int maxIpConnectionCount, bool antiDDosStatus)
        {
            if (!antiDDosStatus)
                return true;

            string iP = sock.RemoteEndPoint.ToString().Split(':')[0];

            if (iP == _mLastIpBlocked)
                return false;

            if (GetConnectionAmount(iP) > maxIpConnectionCount)
            {
                Writer.WriteLine(iP + " was banned by Anti-DDoS system.", "Yupi.Security", ConsoleColor.Blue);

                _mLastIpBlocked = iP;

                return false;
            }
            int freeConnectionId = GetFreeConnectionId();

            if (freeConnectionId < 0)
                return false;

            _mConnectionStorage[freeConnectionId] = iP;

            return true;
        }
Example #18
0
 //处理服务器收到的信息数据,返回gameuser信息
 public static GameUser InfoDataDeal(MySQLCtrl mySQLCtrl, Socket socket, string infoStr)
 {
     string[] strTemp = DataCtrl.SegmentData(infoStr);
     GameUser gameuser = new GameUser();
     switch (strTemp[0])
     {
         //收到注册数据
         case "0":
             string[] infos = DataCtrl.SegmentData(infoStr.Substring(2));
             if (mySQLCtrl.IsExistInDb(infos[0]))
             { gameuser.Status = "0|0|0|注册邮箱已存在|"; return gameuser; }
             if (mySQLCtrl.IsNickNameExistInDb(infos[1]))
             { gameuser.Status = "0|0|0|注册昵称已存在|"; return gameuser; }
             RegisterDeal(mySQLCtrl, socket, infos, out gameuser);
             return gameuser;
         //收到登陆数据
         case "1":
             string[] loadInfo = DataCtrl.SegmentData(infoStr.Substring(2));
             if (!mySQLCtrl.IsExistInDb(loadInfo[0]))
             { gameuser.Status = "0|1|0|登录邮箱未注册|"; return gameuser; }
             SignDeal(mySQLCtrl, socket, loadInfo, out gameuser);
             return gameuser;
         default: return null;
     }
 }
        /// <summary>
        /// Accepts incoming npc service connection.
        /// </summary>
        /// <param name="s">Accepted <see cref="Socket"/> object.</param>
        internal static void AcceptConnection( Socket s )
        {
            if ( s == null || !s.Connected )
                return;

            if ( !Active )
            {
                NetworkHelper.RemoteServiceInfo info = NetworkHelper.GetServiceInfo(s);

                if ( info.ServiceType == ServiceType.NpcService )
                {
                    m_NpcServerConnection = new InnerNetworkClient(info.ServiceId, info.ServiceType, s);

                    NpcServiceRequestsHandlers nsrh = new NpcServiceRequestsHandlers(ref m_NpcServerConnection);
                    //m_NpcServerConnection.OnDisconnected += new OnDisconnectedEventHandler(NpcServerConnection_OnDisconnected);
                    m_NpcServerConnection.HandleDelegate = nsrh.Handle;
                    m_NpcServerConnection.Send(new InitializeResponse(Settings.Default.ServiceUniqueID, ( byte )ServiceType.GameService, InitializeResponse.Accepted).ToPacket());

                    Active = true;

                    Logger.WriteLine(Source.InnerNetwork, "Connection accepted for {0} (0x{1})", info.ServiceType, info.ServiceId.ToString("x2"));

                }
            }
        }
Example #20
0
        /// <summary>
        /// 创建房间数据处理        
        /// </summary>
        /// <param name="roomSeatSockets">要操作的socket字典</param>
        /// <param name="roomNum">要操作的房间号</param>
        /// <param name="socket">对应的客户端socket</param>
        /// <param name="roomStr">对应的接收到的房间数据</param>
        /// <returns>成功返回true,否则返回false</returns>
        public static string RoomDataDeal(GameDataCenter gameDataCenter, Socket socket, string roomStr)
        {
            string[] strTemp = DataCtrl.SegmentData(roomStr);
            switch (strTemp[0])
            {
                //创建房间的信息,房间号++,建立socket的list,加入当前socket,将当前list加入dic,如果对应的房间号的list包含此socket,加入对应的playerdata,返回true,否则,返回false。
                case "0":
                    int roomNum = 1;
                    while(gameDataCenter.RoomDataDic.Keys.Contains(roomNum))
                    {
                        roomNum++;
                    }
                    gameDataCenter.RoomNum= roomNum;
                    List<Socket> l = new List<Socket>();
                    l.Add(socket);
                    gameDataCenter.RoomSeatSockets.Add(gameDataCenter.RoomNum, l);
                    if (gameDataCenter.RoomSeatSockets[gameDataCenter.RoomNum].Contains(socket))
                    {
                        GameRoomData gameRoomData = new GameRoomData();
                        PlayerData playerData = new PlayerData(1, gameDataCenter.MailNickDic[strTemp[1]],strTemp[1],socket);
                        playerData.IsKing = true;
                        gameRoomData.PlayerDataDic.Add(1,playerData);
                        gameDataCenter.RoomDataDic.Add(gameDataCenter.RoomNum, gameRoomData);
                        //更新所有的在大厅中的人的信息,同时更新特定房间的人的信息
                        RoomDataPushAll(gameDataCenter);
                        RoomDataPush(gameDataCenter, roomNum);
                        return "1|0|1|" + gameDataCenter.RoomNum.ToString() + "|" + gameDataCenter.RoomSeatSockets[gameDataCenter.RoomNum].Count.ToString() + "|";

                    }
                    else
                    {

                        gameDataCenter.RoomNum--;
                        return "1|0|0|创建失败|";
                    }
                //加入房间的信息,先取得房间号i,判断房间号i存在否,存在则将此socket加入list,如果此list含此socket,返回true。
                case "1":
                    int i;
                    int.TryParse(strTemp[1], out i);
                    if (!gameDataCenter.RoomSeatSockets.Keys.Contains(i)) { return "1|1|0|加入失败|"; }
                    gameDataCenter.RoomSeatSockets[i].Add(socket);
                    if (gameDataCenter.RoomSeatSockets[i].Contains(socket))
                    {
                        PlayerData playerData = new PlayerData(gameDataCenter.RoomSeatSockets[i].Count, gameDataCenter.MailNickDic[strTemp[1]], strTemp[1],socket);
                        gameDataCenter.RoomDataDic[i].PlayerDataDic.Add(gameDataCenter.RoomDataDic[i].PlayerDataDic.Count+1, playerData);
                        //更新所有的在大厅中的人的信息,同时更新特定房间的人的信息
                        RoomDataPushAll(gameDataCenter);
                        RoomDataPush(gameDataCenter, i);
                        return "1|1|1|" + i + "|" + gameDataCenter.RoomSeatSockets[i].Count.ToString() + "|"; }
                    else
                    { return "1|1|0|加入失败|"; }
                //更新房间信息
                case "2":
                    string strRoomDataUpdate = RoomDataUpdate(gameDataCenter, socket, strTemp);
                    return strRoomDataUpdate;

                default: return "未知错误";

            }
        }
 public ClientProcessor(Socket skt)
 {
     this.skt = skt;
     ReceiveKey =
         new RC4(new byte[] {0x31, 0x1f, 0x80, 0x69, 0x14, 0x51, 0xc7, 0x1b, 0x09, 0xa1, 0x3a, 0x2a, 0x6e});
     SendKey = new RC4(new byte[] {0x72, 0xc5, 0x58, 0x3c, 0xaf, 0xb6, 0x81, 0x89, 0x95, 0xcb, 0xd7, 0x4b, 0x80});
 }
Example #22
0
//		public Socket(AddressFamily af, SocketType st, ProtocolType pt)
//		{
//			this.sock = new Sock(af, st, pt);
//			this.sock.Connect();
//		}

		public Socket(string host, int port)
		{	
			IPEndPoint ep = new IPEndPoint(Dns.GetHostByName(host).AddressList[0], port);
			this.sock = new Sock(ep.AddressFamily,
			SocketType.Stream, ProtocolType.Tcp);
			this.sock.Connect(ep);
		}
        internal Connection(Socket ClientSocket, NetworkStream ClientStream)
        {
            this.ClientSocket = ClientSocket;
            this.ClientStream = ClientStream;

            this.Reader = new WebSocketFrameReader(ClientStream);
        }
Example #24
0
 public void Start()
 {
     _layerFactory = new OwinHandlerFactory(_parameters.OwinApp, _parameters.OwinCapabilities);
     _ipIsLocalChecker = new IpIsLocalChecker();
     _connectionAllocationStrategy = _parameters.ConnectionAllocationStrategy;
     var isSsl = _parameters.Certificate != null;
     _layerFactory = new Transport2HttpFactory(_parameters.BufferSize, isSsl, _parameters.ServerHeader, _ipIsLocalChecker, _layerFactory);
     if (isSsl)
     {
         _layerFactory = new SslTransportFactory(_parameters, _layerFactory);
     }
     ListenSocket = new Socket(_parameters.EndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     var start = DateTime.UtcNow;
     while (true)
     {
         try
         {
             ListenSocket.Bind(_parameters.EndPoint);
             break;
         }
         catch when(start + _parameters.RetrySocketBindingTime > DateTime.UtcNow)
         {
         }
         Thread.Sleep(50);
     }
     ListenSocket.Listen(100);
     var initialConnectionCount = _connectionAllocationStrategy.CalculateNewConnectionCount(0, 0);
     AllocatedConnections = initialConnectionCount;
     _blocks.Add(new ConnectionBlock(this, _layerFactory, initialConnectionCount));
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="ServerContext"/> class.
 /// </summary>
 /// <param name="server">The server.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="serverSocket">The server socket.</param>
 internal ServerContext(StandardServer server, IServerConfiguration configuration, Socket serverSocket)
 {
     this.ListeningSocket = serverSocket;
     this.Server = server;
     this.windowsServer = server;
     this.Configuration = configuration;
 }
Example #26
0
 public Client(Socket pSocket, byte pWorld, byte pChannel, string pType)
     : base(pSocket, pSocket.RemoteEndPoint.ToString())
 {
     this.World = pWorld;
     this.Channel = pChannel;
     this.Type = pType;
 }
 public WebSocketConnection(Socket socket, WebSocketWrapper websocket, SubProtocolModelFactoryWrapper modelfactory)
 {
     Sender = new Sender(socket, websocket);
     Receiver = new Receiver(socket, websocket, modelfactory);
     Sender.Connection = this;
     Receiver.Connection = this;
 }
 public WebSocketConnection(Socket socket, WebSocketWrapper websocket)
 {
     Sender = new Sender(socket, websocket);
     Receiver = new Receiver(socket, websocket);
     Sender.Connection = this;
     Receiver.Connection = this;
 }
        /// <summary>
        /// Initialises a new instance of the <see cref="LiveSocketMessageStream"/> class.
        /// </summary>
        /// <param name="socket">The stream socket.</param>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when <paramref name="socket"/> is <see langword="null"/>.
        /// </exception>
        public LiveSocketMessageStream(Socket socket)
        {
            Guard.NotNull(socket, "socket");

            Socket = socket;
            Socket.NoDelay = true;
        }
Example #30
-1
 public Connection(GameServer server, Socket socket)
 {
     _socket = socket;
     _server = server;
     _socket.BeginReceive(buffer, 0, 256, SocketFlags.None, new AsyncCallback(ReceiveData), _socket);
     _socket.BeginDisconnect(false, new AsyncCallback(Disconnect), null);
 }