private void InternalReceve(IAsyncResult AR) { SocketError SE = SocketError.SocketError; int bytes = NetworkSocket?.EndReceive(AR, out SE) ?? 0; if (SE != SocketError.Success) { Disconnect(new SocketException()); return; } byte[] packet = Defragger.Process(bytes); ReceveWithDefragger(); if (packet != null) { try { IPacket pack = Packager.Unpack(packet, PackagingConfiguration); ReceveCallback(this, pack); } catch (Exception ex) { Disconnect(ex); return; } } }
private void HandleSendQueue() { QueuedPacket packet = null; lock (SyncLock) { packet = SendQueue.Dequeue(); } if (packet != null && packet.Data != null) { var se = SocketError.SocketError; NetworkSocket?.Send(packet.Data, 0, packet.Data.Length, SocketFlags.None, out se); if (se != SocketError.Success) { Disconnect(new SocketException()); return; } else { packet.HasBeenSent(this); } } }
private void InternalReceve(IAsyncResult at) { var se = SocketError.SocketError; var bytes = NetworkSocket?.EndReceive(at, out se) ?? 0; if (se != SocketError.Success) { Disconnect(new SocketException()); return; } var packet = Defragger.Process(bytes); ReceiveWithDefragger(); if (packet != null) { try { var pack = Packager.Unpack(packet, PackagingConfiguration); ReceveCallback(this, pack); } catch (Exception ex) { Disconnect(ex); return; } } }
public virtual void Shutdown(string reason) { LogWrite("Performing shutdown (" + reason + ")"); //#if DEBUG // just send all delayed packets; since we won't have the possibility to do it after socket is closed SendDelayedPackets(NetTime.Now + this.SimulatedMinimumLatency + this.SimulatedLatencyVariance + 1000.0); //#endif try { if (m_socket != null) { // This throws an exception under mono for linux, so we just ingnore it. try { //m_socket.Shutdown(SocketShutdown.Receive); } catch (SocketException) {} m_socket.Close(2); } } finally { m_socket = null; m_isBound = false; } m_shutdownComplete = true; LogWrite("Socket closed"); }
public void Dispose() { if (NetworkSocket != null && NetworkSocket.Connected) { NetworkSocket.Shutdown(SocketShutdown.Both); } }
public void Send(params object[] args) { try { byte[] serilisedData = Formatter.Serialize(args); if (Encryption != null) { serilisedData = Encryption.Encrypt(serilisedData); } byte[] Packet = null; using (MemoryStream packetStream = new MemoryStream()) using (BinaryWriter packetWriter = new BinaryWriter(packetStream)) { packetWriter.Write(serilisedData.Length); packetWriter.Write(serilisedData); Packet = packetStream.ToArray(); } NetworkSocket.BeginSend(Packet, 0, Packet.Length, SocketFlags.None, EndSend, null); } catch { //Not connected } }
public static unsafe int WriteSocket(NetworkSocket socket, byte[] data, NetworkEndPoint endPoint) { if (data == null) throw new ArgumentNullException(nameof(data)); fixed(byte *ptr = data) return(Internal_WriteSocket(ref socket, ptr, (uint)data.Length, &endPoint)); }
public static unsafe int ReadSocket(NetworkSocket socket, byte[] buffer, NetworkEndPoint endPoint) { if (buffer == null) throw new ArgumentNullException(nameof(buffer)); fixed(byte *ptr = buffer) return(Internal_ReadSocket(ref socket, ptr, (uint)buffer.Length, &endPoint)); }
public void Listen(int backlog = 100) { NetworkSocket.Bind(ServerSettings.ServerEndPoint); NetworkSocket.Listen(backlog); Begin(NetworkSocket); }
public void OnExit() { NetworkSocket.UnregisterOnConnectionEstablishedCallback(OnConnection); NetworkHandlers.Clear(); InputHandlers.Clear(); }
public void Init() { Handlers = new HandlersManager(); MatchServerIPs = new Dictionary <int, string>(); DisconnectedMatchServers = new List <int>(); NetworkSocket.RegisterOnDisconnectionCallback(OnDisconnection); }
private void InternalReceive(IAsyncResult ar) { SocketError se = SocketError.SocketError; int bytes = NetworkSocket?.EndReceive(ar, out se) ?? 0; if (se != SocketError.Success) { Disconnect(new SocketException()); return; } byte[] packet = _defragger.Process(bytes); ReceiveWithDefragger(); if (packet == null) { return; } try { IPacket pack = Packager.Unpack(packet, PackagingConfiguration); _receiveCallback(this, pack); } catch (Exception ex) { Disconnect(ex); return; } }
public async void Client_RequestedStreamRead(object sender, NetworkSocket.RequestStreamReadArgs args) { NetworkSocket client = sender as NetworkSocket; byte[] buff = new byte[args.ReadLen]; int bytesRead = 0; //We need to determine if localhost is the host of the files, otherwise we need to forward the request //onto the host of the files if (DoesTokenExist(args.Token)) { try { bytesRead = await ReadStream(args.Token, args.File, buff, 0, args.ReadLen); } catch (Exception ex) { ISLogger.Write("Failed to read stream: " + ex.Message); ISLogger.Write(ex.StackTrace); client.SendFileErrorResponse(args.NetworkMessageId, "An error occurred while reading from stream: " + ex.Message); return; } } if (bytesRead != buff.Length) { //resize the buffer so we don't send a buffer that ends with empty data. byte[] resizedBuffer = new byte[bytesRead]; Buffer.BlockCopy(buff, 0, resizedBuffer, 0, bytesRead); buff = resizedBuffer; } client.SendReadRequestResponse(args.NetworkMessageId, buff); }
private void HandleReceve(IAsyncResult AR) { int packetSize = 0; try { packetSize = NetworkSocket.EndReceive(AR); } catch { OnDisconnect?.Invoke(this); return; } using (MemoryStream ms = new MemoryStream(PacketBuffer, 0, packetSize)) using (BinaryReader br = new BinaryReader(ms)) { while (ms.Position != ms.Length) { int len = br.ReadInt32(); if (CurrentPacketLength == 0) { if (len <= 0) { NetworkSocket.BeginReceive(PacketBuffer, 0, PacketBuffer.Length, SocketFlags.None, RetrieveCallback, null); return; } int cur = (int)(ms.Length - ms.Position); if (cur >= len) { OnDataRetrieve?.Invoke(br.ReadBytes(len)); } else { CurrentPacketLength = len; PacketConstructor.Write(br.ReadBytes(cur), 0, cur); } } else { int cur = (int)(ms.Length - ms.Position); int neededpackets = (int)(CurrentPacketLength - PacketConstructor.Length); if (cur >= neededpackets) { PacketConstructor.Write(br.ReadBytes(neededpackets), 0, neededpackets); OnDataRetrieve?.Invoke(PacketConstructor.ToArray()); PacketConstructor = new MemoryStream(); } else { PacketConstructor.Write(br.ReadBytes(cur), 0, cur); } } } } NetworkSocket.BeginReceive(PacketBuffer, 0, PacketBuffer.Length, SocketFlags.None, RetrieveCallback, null); }
public void Activate() { // Handlers NetworkHandlers.Add <AuthentificationMessage>(60000, OnAuthentificationRequestReceived); NetworkSocket.RegisterOnDisconnectionCallback(OnConnectionLost); }
// Callback when the ping method times out private void OnTimeOut(object state) { HasPingCommandTimedOut = true; if (NetworkSocket != null) { NetworkSocket.Close(); } }
private static void KickPlayer(int index) { Console.WriteLine("Kicking Player index: " + index); ByteBuffer buffer = new ByteBuffer(); buffer.WriteLong((long)ServerPackets.KICK); buffer.WriteLong(index); NetworkSocket.SendDataTo(0, buffer.ToArray()); }
public void Init() { Handlers = new HandlersManager(); KnownClients = new Dictionary <string, ClientAccountInfo>(); // TODO : Ecrire une fonction pour charger cette liste à partir d'un fichier / base de données. OnlineClients = new Dictionary <int, ClientAccountInfo>(); DisconnectedClients = new List <int>(); NetworkSocket.RegisterOnDisconnectionCallback(OnDisconnection); }
/// <summary> /// Uses defagger to receve packets. /// </summary> private void ReceiveWithDefragger() { NetworkSocket.BeginReceive(Defragger.ReceveBuffer, Defragger.BufferIndex, Defragger.BytesToReceve, SocketFlags.None, out SocketError SE, InternalReceve, null); if (SE != SocketError.Success) { Disconnect(new SocketException()); } }
public void Shutdown() { Log.Information("Server socket closing..."); NetworkSocket?.Shutdown("Server going down for quit"); NetworkSocket = null; NetworkPipe = null; NetConfiguration = null; }
public void SetUpServerConnection() { if (_networkSocket != null) { return; } _networkSocket = new NetworkSocket(SERVER_IP, SERVER_PORT, BUFFER_SIZE); }
/// <summary> /// Shutdown the network client /// </summary> public void Shutdown() { Log.Information("stopping Client NetworkSocket..."); NetworkSocket?.Shutdown("Client application exited"); NetworkSocket = null; NetConfiguration = null; MessagePipe = null; }
public void Dispose() { if (NetworkSocket.Connected) { NetworkSocket.Shutdown(SocketShutdown.Both); NetworkSocket.Disconnect(true); } NetworkSocket.Close(1000); }
public void StartRetrieve() { if (RetrieveCallback != null) { return; } RetrieveCallback = new AsyncCallback(HandleReceve); NetworkSocket.BeginReceive(PacketBuffer, 0, PacketBuffer.Length, SocketFlags.None, RetrieveCallback, null); }
public void Disconnect() { try { NetworkSocket.Close(); } catch { } }
public void Disconnect(Exception ex) { if (NetworkSocket != null) { NetworkSocket.Shutdown(SocketShutdown.Both); NetworkSocket.Dispose(); NetworkSocket = null; OnDisconnect?.Invoke(this, ex); } }
public void Reception() { int recHostID; int recConnectionID; int recChannelID; int recSize; byte error; byte[] buffer = new byte[STANDARD_BUFFER_SIZE]; NetworkEventType e; e = NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, STANDARD_BUFFER_SIZE, out recSize, out error); if (error != 0) { if ((NetworkError)error == NetworkError.MessageToLong) { // Re-recevoir le message avec un buffer plus grand. buffer = new byte[FRAGMENTED_BUFFER_SIZE]; e = NetworkTransport.Receive(out recHostID, out recConnectionID, out recChannelID, buffer, FRAGMENTED_BUFFER_SIZE, out recSize, out error); } else { Debugger.Log("ERREUR - NETWORKRECEIVER - RECEPTION() - " + (NetworkError)error); } } switch (e) { case (NetworkEventType.ConnectEvent): Debugger.Log("Connexion établie. ID = " + recConnectionID); NetworkSocket.OnConnectionEstablished(recConnectionID); break; case (NetworkEventType.DisconnectEvent): Debugger.Log("Connexion fermée. ID = " + recConnectionID); NetworkSocket.OnDisconnection(recConnectionID); break; case (NetworkEventType.DataEvent): // Des données ont été reçues. D'abord, construire l'objet ReceivedMessage en reconstituant le NetworkMessage : MemoryStream stream = new MemoryStream(buffer); object info = Formatter.Deserialize(stream); ReceivedMessage msg = new ReceivedMessage((NetworkMessage)info); // Ensuite, remplir l'objet NetworkMessageInfo de msg : msg.RecInfo.ConnectionID = recConnectionID; //_____________________________________________________ // Enfin, envoyer le ReceivedMessage au MessageReader. MessageReader.AddMessageToQueue(msg); break; } }
public void StartListen() { Logger.Info("Starting service..."); IPEndPoint endPoint = GetLocalEndPoint(); NetworkSocket.Bind(endPoint); NetworkSocket.Listen(_backlog); StartAccept(); }
string Password; // Mot de passe qu'on tente d'utiliser. // FONCTIONS DE CLIENTSTATE public void OnEntry() { if (BloodAndBileEngine.WorldState.Map.Maps == null) { BloodAndBileEngine.WorldState.Map.LoadMaps(); } InputHandlers.Add("Login", Login); InputHandlers.Add("LoginToMatchServer", LoginToMatchServer); // Permet de rapidement tester le Match Server (et surtout de ne pas avoir besoin de lancer un Master Server.) NetworkSocket.RegisterOnConnectionEstablishedCallback(OnConnection); NetworkHandlers.Add <BloodAndBileEngine.Networking.NetworkMessages.ConditionCheckResponseMessage>(60001, OnAuthentificationResponse); }
public void OnAuthorization(NetworkSocket.Fast.ActionContext filterContext) { var valid = filterContext.Session.TagData.TryGet<bool>("Logined"); if (valid == false) { // 直接关闭客户端的连接 // filterContext.Session.Close(); // 以异常方式提示客户端 throw new Exception("未登录就尝试请求其它服务"); } }
public static bool InitializeEngine() { NetworkSocket.Initialize(); try { background = new EngineObject($"{Common.Configuration.GamePath}/Data/background.png", 1024, 768); background.Size = new Size2(1024, 768); background.SourceRect = new Rectangle(0, 0, 1024, 720); DataManager.Initialize(); WindowTalent.Initialize(); WindowSkill.Initialize(); WindowPin.Initialize(); WindowCash.Initialize(); WindowMail.Initialize(); WindowSelectedItem.Initialize(); WindowViewTalent.Initialize(); //Carrega os dados de classe. ClasseManager.Initialize(); //Carrega os dados de npc. NpcManager.OpenData(); //Carrega os dados de experiencia ExperienceManager.Read(); EngineFont.Initialize(); EngineMessageBox.Initialize(); EngineInputBox.Initialize(); EngineMultimedia.Initialize(); WindowLogin.Initialize(); WindowServer.Initialize(); WindowCharacter.Initialize(); WindowNewCharacter.Initialize(); WindowGame.Initialize(); WindowViewItem.Initialize(); // EngineMultimedia.PlayMusic(0, true); GameState = 1; return(true); } catch (Exception ex) { MessageBox.Show(ex.Message); return(false); } }
/// <summary> /// 收到http请求 /// </summary> /// <param name="context">上下文</param> /// <param name="requestContext">请求上下文</param> protected override void OnHttpRequest(IContenxt context, NetworkSocket.Http.RequestContext requestContext) { var request = requestContext.Request; var response = requestContext.Response; if (AppConfig.PathPattern.IsMatch(request.Path) == false) { var message = "路径不匹配,数据未转发 .."; response.Write(message); Console.WriteLine(message); } else { var fastSessions = context.AllSessions.FilterWrappers<FastSession>().ToArray(); foreach (var session in fastSessions) { this.PushRequest(session, request); } var message = string.Format("数据已转发到{0}到客户端 ..", fastSessions.Length); response.Write(message); Console.WriteLine(message); } }