상속: IDisposable
예제 #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);
 }
        /// <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;
        }
예제 #3
0
 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;
 }
예제 #4
0
파일: socket.cs 프로젝트: Season02/MK2.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);
            }
        }
예제 #5
0
 public ClientConnection(Socket socket)
     : base(socket)
 {
     DisconnectedEvent += ClientConnection_DisconnectedEvent;
     m_LittleEndian = true;
     Logger.Trace("Client {0}: Connected", this);
 }
 public ProcessQueue(int _cardNo, Player _user, Socket _userSocket, Player _target)
 {
     cardNo = _cardNo;
     user = _user;
     target = _target;
     userSocket = _userSocket;
 }
예제 #7
0
 public WebSocketConnection(Socket socket, WebSocketWrapper websocket)
 {
     Sender = new Sender(socket, websocket);
     Receiver = new Receiver(socket, websocket);
     Sender.Connection = this;
     Receiver.Connection = this;
 }
        internal Connection(Socket ClientSocket, NetworkStream ClientStream)
        {
            this.ClientSocket = ClientSocket;
            this.ClientStream = ClientStream;

            this.Reader = new WebSocketFrameReader(ClientStream);
        }
        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;
        }
예제 #10
0
 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});
 }
예제 #11
0
 public AbstractSession(Socket sck)
 {
     this.Actived = false;
     this.Socket = sck;
     this.Handle = sck.Handle.ToInt32();
     this.RemoteEndpoint = sck.RemoteEndPoint.ToString();
 }
예제 #12
0
        /// <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"));

                }
            }
        }
예제 #13
0
 public OnlineUser(Socket socket, String username, String token, String publicKey)
 {
     WorkSocket = socket;
     Username = username;
     this.token = token;
     PublicKey = publicKey;
 }
예제 #14
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;
        }
예제 #15
0
        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;
            }
        }
예제 #16
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;
 }
예제 #17
0
파일: Socket.cs 프로젝트: viticm/pap2
//		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);
		}
예제 #18
0
파일: Server.cs 프로젝트: nobitagamer/Nowin
 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));
 }
예제 #19
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;
     }
 }
예제 #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 "未知错误";

            }
        }
예제 #21
0
 public void Dispose()
 {
     Socket.Disconnect(false);
     Socket.Shutdown(SocketShutdown.Both);
     Socket.Close();
     Socket = null;
 }
        // 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;
 }
예제 #24
0
 public Client(Socket s)
 {
     clientSocket = s;
     //启动一个线程处理客户端的数据接收
     t = new Thread(ReceiveMessage);
     t.Start();
 }
예제 #25
0
        /// <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;
            }
        }
예제 #26
0
 public WorkerProxy(NagCoordinator coordinator, Socket socket)
 {
     Worker = new TCPConnection(socket, false, ProcesLine, null);
     NagCoordinator = coordinator;
     State = ConnectionState.Negotiating;
     Negotiate();
 }
예제 #27
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 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;
        }
예제 #29
0
 /// <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;
 }
 protected SocketConnectionServerDispatcher(System.Net.Sockets.Socket connect) : base(connect)
 {
 }
예제 #31
0
 /// <summary>
 ///  Sends the specified number of bytes of data to a connected <see cref="Socket" />, starting at the specified offset, and using the specified <see cref="SocketFlags" />.
 /// </summary>
 /// <param name="data">An string of type <see cref="string" /> that contains the data to be sent.</param>
 /// <param name="socketFlags">A bitwise combination of the <see cref="SocketFlags" /> values.</param>
 /// <param name="socketError">A <see cref="SocketError" /> object that stores the socket error.</param>
 /// <param name="encoding">The <see cref="Encoding"/> for data.</param>
 /// <returns>The number of bytes sent to the <see cref="Socket"/>.</returns>
 public static int Send(this System.Net.Sockets.Socket socket, string data, SocketFlags socketFlags, out SocketError socketError, Encoding encoding)
 {
     byte[] buffers = encoding.GetBytes(data);
     return(socket.Send(buffers, 0, buffers.Length, socketFlags, out socketError));
 }
예제 #32
0
 /// <inheritdoc/>
 protected abstract IoSession NewSession(IoProcessor <SocketSession> processor, System.Net.Sockets.Socket socket);
예제 #33
0
 public Socket(Sock sock)
 {
     this.sock = sock;
 }
예제 #34
0
 public UdpListener(IPEndPoint endPoint)
 {
     _endPoint = endPoint;
     _socket   = new System.Net.Sockets.Socket(_endPoint.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
     _socket.Bind(_endPoint);
 }
예제 #35
0
 /// <summary>
 ///  Determine whether data is ready to be read
 /// </summary>
 public static bool IsDataAvailable(this System.Net.Sockets.Socket s)
 {
     return(s.Poll(1000, SelectMode.SelectRead) && (s.Available > 0));
 }
예제 #36
0
        /// <inheritdoc/>
        protected override IoSession NewSession(IoProcessor <SocketSession> processor, System.Net.Sockets.Socket socket)
        {
            SocketAsyncEventArgsBuffer readBuffer  = _readWritePool.Pop();
            SocketAsyncEventArgsBuffer writeBuffer = _readWritePool.Pop();

            if (readBuffer == null)
            {
                readBuffer = (SocketAsyncEventArgsBuffer)
                             SocketAsyncEventArgsBufferAllocator.Instance.Allocate(SessionConfig.ReadBufferSize);
                readBuffer.SocketAsyncEventArgs.Completed += readWriteEventArg_Completed;
            }

            if (writeBuffer == null)
            {
                writeBuffer = (SocketAsyncEventArgsBuffer)
                              SocketAsyncEventArgsBufferAllocator.Instance.Allocate(SessionConfig.ReadBufferSize);
                writeBuffer.SocketAsyncEventArgs.Completed += readWriteEventArg_Completed;
            }

            return(new AsyncSocketSession(this, processor, socket, readBuffer, writeBuffer, ReuseBuffer));
        }
예제 #37
0
파일: Peer.cs 프로젝트: bmjoy/Regulus
 public Peer(System.Net.Sockets.Socket socket)
 {
     _SocketErrorEvent += (e) => { };
     Socket             = socket;
 }
 public SendingContext(System.Net.Sockets.Socket s, Core.File.IFileRegion f)
 {
     socket = s;
     buffer = null;
     file   = f;
 }
예제 #39
0
 /// <summary>
 /// Sends data to a connected <see cref="Socket" /> using the specified <see cref="SocketFlags" />.
 /// </summary>
 /// <param name="data">An string of type <see cref="string" /> that contains the data to be sent.</param>
 /// <param name="socketFlags">A bitwise combination of the <see cref="SocketFlags" /> values.</param>
 /// <param name="encoding">The <see cref="Encoding"/> for data.</param>
 /// <returns>The number of bytes sent to the <see cref="Socket"/>.</returns>
 public static int Send(this System.Net.Sockets.Socket socket, string data, SocketFlags socketFlags, Encoding encoding)
 {
     byte[] buffers = encoding.GetBytes(data);
     return(socket.Send(buffers, socketFlags));
 }
 public AsyncSocketSession(IoService service, IoProcessor <SocketSession> processor,
                           System.Net.Sockets.Socket socket, Boolean reuseBuffer)
     : base(service, processor, new SessionConfigImpl(socket), socket, socket.LocalEndPoint, socket.RemoteEndPoint, reuseBuffer)
 {
     _readBuffer = new Byte[service.SessionConfig.ReadBufferSize];
 }
 public SendingContext(System.Net.Sockets.Socket s, IoBuffer b)
 {
     socket = s;
     buffer = b;
     file   = null;
 }
예제 #42
0
 public void WaitAccess()
 {
     m_clientSocket = m_serverSocket.Accept();
 }
예제 #43
0
 public AsyncUserToken(System.Net.Sockets.Socket socket)
 {
     this.Socket = socket;
     this.Buffer = new List <byte>();
 }
예제 #44
0
        /// <summary>
        /// Create a new instance of the server context type.
        /// </summary>
        /// <param name="clientSocket">The current state, contains a socket client.</param>
        private void CreateServerContext(System.Net.Sockets.Socket clientSocket)
        {
            ServerContext socketServerContext = null;

            try
            {
                // Clear last error.
                ClearLastError();

                // Create a new instance of the server context type
                socketServerContext = (ServerContext)Nequeo.Reflection.TypeAccessor.CreateInstance(_serverContext);

                // Assign the accepted socket.
                socketServerContext.Socket                  = clientSocket;
                socketServerContext.UseSslConnection        = _useSslConnection;
                socketServerContext.X509Certificate         = _sslCertificate;
                socketServerContext.Name                    = _serverName;
                socketServerContext.SslProtocols            = _sslProtocols;
                socketServerContext.SocketType              = _socketType;
                socketServerContext.ProtocolType            = _protocolType;
                socketServerContext.ReceiveSocketFlags      = _receiveSocketFlags;
                socketServerContext.SendSocketFlags         = _sendSocketFlags;
                socketServerContext.SendToServerHandler     = _sendToServerHandler;
                socketServerContext.SendToServerInfoHandler = _sendToServerInfoHandler;
                socketServerContext.BeginSslAuthenticate    = _beginSslAuthentication;
                socketServerContext.ReadBufferSize          = READ_BUFFER_SIZE;
                socketServerContext.WriteBufferSize         = WRITE_BUFFER_SIZE;
                socketServerContext.Server                  = this;

                // if a time out has been set.
                if (_timeOut > 0)
                {
                    socketServerContext.TimeOut = _timeOut;
                }

                // Create a new client data receive handler, this event
                // handles commands from the current client.
                socketServerContext.OnCommandSend +=
                    new ServerContextHandler(SocketServer_OnCommandSend);

                // Increment the count.
                IncrementCount();

                // Initialise the connection.
                socketServerContext.InitialiseThread();

                try
                {
                    // Send the new connection to the caller.
                    if (OnClientConnected != null)
                    {
                        OnClientConnected(this, socketServerContext);
                    }
                }
                catch { }
            }
            catch (Exception ex)
            {
                // Clean-up if error.
                if (socketServerContext != null)
                {
                    socketServerContext.Dispose();
                }

                socketServerContext = null;
                SetLastError(ex);
            }
        }
예제 #45
0
 public void CreateSocketAndStandBy()
 {
     m_serverSocket = new System.Net.Sockets.Socket(m_ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
     m_serverSocket.Bind(m_localEndPoint);
     m_serverSocket.Listen(10);
 }
예제 #46
0
        private static void Socket_OnReceivingEvent(System.Net.Sockets.Socket S, byte[] Packet)
        {
            int packetNumber = BitConverter.ToUInt16(Packet, 2);

            switch (packetNumber)
            {
            case 1000:
                Connect   connectPacket = new Connect(Packet);
                Character c             = new Character(connectPacket.Character, S);
                c.CharacterID             = (byte)charactersPool.Count;
                connectPacket.CharacterID = c.CharacterID;
                c.CharacterType           = connectPacket.Character;
                socket.Send(S, connectPacket.Packet());
                charactersPool.Add(c);
                if (charactersPool.Count == 2)
                {
                    GroundedObject GO = new GroundedObject();
                    GO.CharacterType = 0;
                    for (int i = 0; i < Constants.enemiesCount; i++)
                    {
                        GO.Buffer[i + 6] = (byte)(ran.Next(0, 3));
                    }
                    for (int i = 0; i < Constants.enemiesCount; i++)
                    {
                        int idx = i * 4 + 50;
                        int v   = ran.Next(-1100, -800);
                        Console.WriteLine("r: " + v);
                        byte[] Val = BitConverter.GetBytes(v);
                        Buffer.BlockCopy(Val, 0, GO.Buffer, idx, Val.Length);
                    }
                    socket.Send(charactersPool[0].socket, GO.Packet());
                    //Thread.Sleep(500);
                    socket.Send(charactersPool[1].socket, GO.Packet());
                    //Thread.Sleep(500);


                    GO.CharacterType = 1;
                    for (int i = 0; i < Constants.ringsCount; i++)
                    {
                        GO.Buffer[i + 6] = (byte)(ran.Next(0, 3));
                    }
                    for (int i = 0; i < Constants.ringsCount; i++)
                    {
                        int    idx = i * 4 + 50;
                        byte[] Val = BitConverter.GetBytes(ran.Next(-1100, -800));
                        Buffer.BlockCopy(Val, 0, GO.Buffer, idx, Val.Length);
                    }
                    socket.Send(charactersPool[0].socket, GO.Packet());
                    //Thread.Sleep(500);
                    socket.Send(charactersPool[1].socket, GO.Packet());
                    //Thread.Sleep(500);

                    socket.Send(charactersPool[0].socket, new GO()
                    {
                        SecondCharacter = (byte)charactersPool[1].CharacterType
                    }.Buffer);

                    socket.Send(charactersPool[1].socket, new GO()
                    {
                        SecondCharacter = (byte)charactersPool[0].CharacterType
                    }.Buffer);
                }
                break;

            case 1006:
                Movement m = new Movement(Packet);
                socket.Send(charactersPool[m.ID].socket, m.Buffer);
                break;

            case 1008:
                Respawn r = new Respawn(Packet);
                if (r.Change == 1)
                {
                    r.lane = (byte)(ran.Next(0, 3));
                }
                socket.Send(charactersPool[0].socket, r.Buffer);
                break;
            }
        }
예제 #47
0
    private static void Connect()
    {
        Task getPrimeNums = new Task(RSA.getPrimeNums);

        getPrimeNums.Start();

        while (localPort == -1 || remotePort == -1 || remoteIpAddress == "-1")
        {
            ;
        }

        try
        {
            listeningSocket = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            Task listeningTask = new Task(Listen);
            listeningTask.Start();

            byte[]   data;
            EndPoint remotePoint = new IPEndPoint(IPAddress.Parse(remoteIpAddress), remotePort);

            if (!Handshake || !wasGettedKey || !wasGettedN || !wasGettedMainKey)
            {
                InfoMessage("Waiting for handshacke...");

                do
                {
                    Thread.Sleep(1000);
                    data = Encoding.Unicode.GetBytes("0");
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(10);
                }       while (!Handshake);

                MyKeys = RSA.getKeys();

                InfoMessage("Sending keys...");

                do
                {
                    data = Encoding.Unicode.GetBytes(Convert.ToString(MyKeys[0]));                     //Отправляем N
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(1000);
                } while (!wasGettedN);

                do
                {
                    data = Encoding.Unicode.GetBytes(Convert.ToString(MyKeys[1]));                     //Отправляем e
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(1000);
                } while (!wasGettedKey);

                InfoMessage("Connecting...");

                do
                {
                    data = Encoding.Unicode.GetBytes(Convert.ToString(PrimeTest.quickMod(
                                                                          MyMainKey, HerOpenKey[1], HerOpenKey[0])));
                    listeningSocket.SendTo(data, remotePoint);
                    Thread.Sleep(1000);
                } while(!wasGettedMainKey);

                Thread.Sleep(3000);
            }
        }
        catch (Exception ex)
        {
            InfoMessage(Convert.ToString(ex));
        }

        InfoMessage("Connected!");
    }
 public clientInformation(System.Net.Sockets.Socket c, Gtk.TreeIter ti)
 {
     client   = c;
     treeIter = ti;
 }
예제 #49
0
 private static void Socket_OnNewConnEvent(System.Net.Sockets.Socket S)
 {
     Console.WriteLine("A new player has joined");
 }
예제 #50
0
 /// <summary>
 /// 初始一个Socket
 /// </summary>
 /// <param name="localEP">监听地址</param>
 /// <param name="callback">当前接受到新消息时回调</param>
 public SocketClient(IPAddress address, int port)
 {
     this.IsDisposable = false;
     IPE    = new IPEndPoint(address, port);
     Socket = new System.Net.Sockets.Socket(IPE.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
 }
예제 #51
0
 TcpSocket(Context context, AddressFamily addressFamily, System.Net.Sockets.Socket socket)
     : base(context, addressFamily, socket)
 {
 }
예제 #52
0
 /// <summary>
 /// Instantiates.
 /// </summary>
 /// <param name="socket">the associated socket</param>
 public ListenerContext(System.Net.Sockets.Socket socket)
 {
     _socket = socket;
 }
예제 #53
0
 /// <summary>
 /// Instantiates.
 /// </summary>
 /// <param name="socket">the associated socket</param>
 /// <param name="remoteEP">the remote endpoint</param>
 /// <param name="sessionInitializer">the funciton to initialize session</param>
 public ConnectorContext(System.Net.Sockets.Socket socket, EndPoint remoteEP, Action <IoSession, IConnectFuture> sessionInitializer)
 {
     _socket             = socket;
     _remoteEP           = remoteEP;
     _sessionInitializer = sessionInitializer;
 }
            /// <summary>
            /// Processes incoming requests
            /// </summary>
            protected void ProcessRequest()
            {
                // accept an incoming connection request and once we have one, spawn a new thread to accept more
                bool newThread = false;

                System.Net.Sockets.Socket clientSocket = null;
                Responder responder = null;

                while (IsRunning && !newThread)
                {
                    try
                    {
                        // process incoming request
                        clientSocket = LocalServer.Accept();
                        clientSocket.ReceiveTimeout = Timeout;
                        clientSocket.SendTimeout    = Timeout;

                        // parse message an create an object containing parsed data
                        responder = new Responder();
                        responder.ClientEndpoint = clientSocket.RemoteEndPoint.ToString();
                        responder.ClientSocket   = clientSocket;

                        Thread t = new Thread(new ThreadStart(ProcessRequest));
                        t.Start();
                        newThread = true;
                    }
                    catch
                    {
                        if (clientSocket != null)
                        {
                            try
                            {
                                clientSocket.Close();
                            }
                            catch { }
                        }
                    }
                }

                // now process the request
                try
                {
                    bool finishedParsing = false;

                    TimeSpan parseStart = Timer.GetMachineTime();

                    while (!finishedParsing)
                    {
                        if (Timer.GetMachineTime() - parseStart > MaxProcessingTime)
                        {
                            return;
                        }

                        // receiving data, add to an array to process later
                        byte[] buffer = new byte[clientSocket.Available];
                        clientSocket.Receive(buffer);

                        finishedParsing = responder.parse(buffer);
                    }

                    // trigger event to get response
                    WebEvent webevent = null;

                    if (responder.Path != null)
                    {
                        webevent = serverManager.GetWebEventById(responder.Path);
                    }

                    if (webevent == null)
                    {
                        webevent = serverManager.DefaultEvent;
                    }

                    responder.webEvent = webevent;

                    webevent.OnWebEventReceived(responder.Path, responder.HttpMethod, responder);
                }
                catch
                {
                }
            }
예제 #55
0
 private void Wudp_weaveUpdateSocketListEvent(System.Net.Sockets.Socket soc)
 {
     SetServerReceiveText("有人加入了");
     AllConnectedClient.Add(soc);
 }
예제 #56
0
 protected virtual void Initialize(NativeSocket socket)
 {
     _delegate = socket;
 }
예제 #57
0
 // 建構函式
 public FTPSession(Socket serverSocket)
 {
     this.serverSocket = serverSocket;
     currentPath       = rootPath;
 }
예제 #58
0
 public ClientThread(System.Net.Sockets.Socket c, Action <byte[]> callback)
 {
     client        = c;
     this.callback = callback;
 }
예제 #59
0
 private void Wudp_weaveDeleteSocketListEvent(System.Net.Sockets.Socket soc)
 {
     SetServerReceiveText("有人退出了");
     AllConnectedClient.Remove(soc);
 }
예제 #60
-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);
 }