//Logout public void Logout() { try { if (isConnected) { char[] response = SendCommand("QUIT "); Print(response); if (statusCode != 221) { throw new FTPException(statusCode + " status : Not Logged Out"); } serverCommandSocket.Disconnect(); } else { throw new IsNotConnectedException("Not Connected"); } } catch (IsNotConnectedException exception) { WriteLine(exception.Message); Logout(); } }
// Método que se llamará SIN PARÁMETROS al crear el hilo del Cliente! => ThreadStart(LaunchLient) public void LaunchClient() { // Interactuar con el cliente clientSocket = new ClientSocket(clienteConectado); // A) SOLICITAR DATOS AL CLIENTE // Enviar solicitud de ingreso de remitente y guardar resultado desde el socket clientSocket.Write("Ingrese remitente:"); string remitente = clientSocket.Read(); // Enviar solicitud de ingreso de texto y guardar resultado desde el socket clientSocket.Write("Ingrese texto:"); string texto = clientSocket.Read(); // B) CREAR EL MENSAJE // Elaboramos el mensaje (DTO) Message mensaje = new Message() { Remitente = remitente, Texto = texto, Tipo = "NORMAL" }; // Para enviar un DTO => DAL MessageDAL messageDAL = MessageDAL.GetInstance(); // GUARDAR EL MENSAJE (DE FORMA SEGURA) lock (messageDAL) { messageDAL.Add(mensaje); } clientSocket.Disconnect(); }
private void Btn_cont_Click(object sender, RoutedEventArgs e) { if (btn_cont.IsChecked == true) { clientSocket = new ClientSocket("127.0.0.1", 10001); clientSocket.OnServerClose -= ClientSocket_OnServerClose; clientSocket.OnServerClose += ClientSocket_OnServerClose; clientSocket.ReceiveData -= ClientSocket_ReceiveData; clientSocket.ReceiveData += ClientSocket_ReceiveData; if (clientSocket.Connect()) { MSG("服务器已经连接"); } else { MSG("服务器连接失败"); btn_cont.IsChecked = false; } } else { clientSocket.Disconnect(); MSG("服务器已经断开连接"); } }
//Connect public bool Connect(string address) { try { this.remoteAddress = address; serverCommandSocket = new ClientSocket(); SocketConnectArgs args = serverCommandSocket.ConnectThread(Dns.GetHostAddresses(address)[0], port); if (!args.isConnected) { throw new FTPCannotConnectException(args.exception.Message); } char[] response = WaitForStatus(); Print(response); statusCode = 100 * (response[0] - '0') + 10 * (response[1] - '0') + (response[2] - '0'); if (statusCode != 220) { serverCommandSocket.Disconnect(); throw new FTPCannotConnectException(args.exception.Message); } return(true); } catch (FTPCannotConnectException exception) { WriteLine(exception); return(false); } }
public void Disconnect() { Disposed = true; ClientSocket.Disconnect(false); ClientSocket.Dispose(); Player?.Dispose(); }
public void Disconnect() { if (mSocket != null) { mSocket.Disconnect(); mSocket = null; } }
public static void Dispose() { Disposed = true; if (ClientSocket.Connected) { ClientSocket.Disconnect(false); } ClientSocket.Dispose(); }
public void TestClientSocketDisconnect() { ClientSocket client = new ClientSocket(); client.BeginConnect(address, port); client.Disconnect(); Assert.IsFalse(client.Connected); }
public void Disconnect() { lock (ClientSocket) { if (ClientSocket.Connected) { ClientSocket.Disconnect(true); } } }
public void Disconnect(string error = null) { if (error != null) { Logger.Error($"[{Username ?? "Anonymous"}] Client disconnected with error: '{error}'"); } ClientSocket?.Disconnect(false); ClientSocket?.Dispose(); Dispose(true); }
public void Quit() { if (_client != null && _client.Connected) { _client.BaseSend($"{FTPCommand.QUIT}"); _client.Disconnect(); _client.Dispose(); } }
public void DisconnectServer() { client.Disconnect(); client.OnConnectEvent -= client_OnConnectEvent; client.OnDisconnectEvent -= client_OnDisconnectEvent; //client.OnMessageEvent -= client_OnMessageEvent; //client.OnReceiveEvent -= client_OnReceiveEvent; _Conenected = false; button1.Text = "连接"; button2.Enabled = false; }
public void Logout() { if (_clientSocket.Connected) { _clientSocket.Disconnect(); } else { throw new SocketException(); } }
//List Files public void ListFilesWithDetails() { try { GetTransferSocket(); if (isConnected) { char[] response = SendCommand("LIST "); Print(response); statusCode = 100 * (response[0] - '0') + 10 * (response[1] - '0') + (response[2] - '0'); if (statusCode != 150) { throw new FTPException(statusCode + " status : unable to List Files"); } response = serverTransferSocket.RecieveStringThread(); Print(response); serverTransferSocket.Disconnect(); serverTransferSocket = null; //response = WaitForStatus(); //Print(response); //statusCode = 100 * (response[0] - '0') + 10 * (response[1] - '0') + (response[2] - '0'); //if (statusCode != 226) //{ // throw new FTPException(statusCode + " status : unable to complete Download"); //} } else { throw new IsNotConnectedException("Not Connected"); } } catch (FTPException exception) { WriteLine(exception.Message); } catch (IsNotConnectedException exception) { WriteLine(exception.Message); Logout(); } }
public void exit() { if (ClientSocket.Connected) { ClientSocket.Send(Encoding.Unicode.GetBytes("离开了房间!\n")); //禁用发送和接受 ClientSocket.Shutdown(SocketShutdown.Both); //关闭套接字,不允许重用 ClientSocket.Disconnect(false); } ClientSocket.Close(); }
public void Dispose() { _handleSocksTaskCts?.Cancel(); if (ClientSocket.Connected) { ClientSocket.Disconnect(false); } if (EndpointSocket?.Connected ?? false) { EndpointSocket.Disconnect(false); } ClientSocket?.Dispose(); EndpointSocket?.Dispose(); }
/// <summary> /// Straight disconnects a client, no warning. Used in final stages of disconnect, or if a client violates protocol. /// </summary> public void Shutdown() { _canReceive = false; TaskScheduler.UnregisterTask(_taskId); if (Verified) { ClientPlayer.Logout(); Server.UnregisterClient(this); } Verified = false; if (_socket.IsConnected) { _socket.Disconnect(""); } }
public override void Detach() { // force disconnect client try { Control.Network.Server.RemoveClient(this); if (ClientSocket != null && ClientSocket.Connected) { try { this.Dispatch(new CommandInput { Text = "DC", WindowStationHandle = this.WindowStationHandle, WindowDesktopHandle = this.WindowDesktopHandle, WindowHandle = this.WindowHandle }); } catch { } try { ClientSocket.Shutdown(SocketShutdown.Receive); ClientSocket.Close(1); } catch { } try { ClientSocket.Disconnect(false); } catch { } ClientSocket = null; } } catch (Exception ex) { Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); } finally { ConnectAlreadySent = false; base.Detach(); } }
public static void Handle(ClientSocket client, byte[] packet) { var id = BitConverter.ToUInt16(packet, 4); var customer = (Customer)client.StateObject; switch (id) { case 1000: ProcessLogin(packet, customer, client); break; case 1002: ProcessTransaction(packet, customer, client); break; default: Console.WriteLine("Invalid packet received from " + client.Socket.RemoteEndPoint); client.Disconnect(); break; } }
/// <summary> /// Основной метод (точка входа) /// </summary> static void Main() { Console.SetCursorPosition(SenderLeft, SenderTop); if (!GetConnect()) { ConsoleMessage("Всего доброго"); Console.ReadLine(); return; } if (!RegisterClient()) { ClientSocket?.Disconnect(false); ClientSocket?.Shutdown(SocketShutdown.Both); ClientSocket?.Close(); ConsoleMessage("Всего доброго"); Console.ReadLine(); return; } var receivingThread = new Thread(() => ReceivingMessages()); receivingThread.Start(); var processingThread = new Thread(() => ProcessingIncomingMessage()); processingThread.Start(); var command = ""; while (command != Datas.ExitCommand.ComKey) { command = ConsoleRead(); CreateMessage(command)?.SendAsync(); } ClientSocket.Disconnect(false); ConsoleMessage("Всего доброго! Для выхода нажмите 'Enteer'"); Console.ReadLine(); receivingThread.Join(); processingThread.Join(); ClientSocket.Shutdown(SocketShutdown.Both); ClientSocket.Close(); }
private void button_Discon_Click(object sender, EventArgs e) { bool isSuccess = false; _client.SendMessage(DataStructure.Command.CmdStop); isSuccess = _client.Disconnect(); if (isSuccess) { button_Connect.Enabled = true; button_Discon.Enabled = false; button_Send.Enabled = false; button_SymbolSend.Enabled = false; button_INIT.Enabled = false; button_START.Enabled = false; button_STOP.Enabled = false; button_1.Enabled = false; button_2.Enabled = false; button_3.Enabled = false; button_4.Enabled = false; button_5.Enabled = false; toolStripStatusLabel.Text = "TEM Disconnect"; } }
private void ClientReceiveEvent(object sender, SocketAsyncEventArgs e) { try { //check for client closure int length = e.BytesTransferred; if (e.BytesTransferred == 0) { Connected = false; ClientSocket.Disconnect(false); } //add the received data to our buffer, in case we receive incomplete segments ClientBuffer.AddRange(e.Buffer.Take(length)); //while theres more than 2 bytes in the buffer while (ClientBuffer.Count > 2) { //get the packet length indicated by those 2 bytes ushort packetLength = (ushort)((ClientBuffer[0] << 8) + ClientBuffer[1]); //if its longer than the buffer size, we havent received the full packet yet if (packetLength > ClientBuffer.Count) { break; } //otherwise, get the packet data and remove it from the buffer List <byte> packetData = ClientBuffer.GetRange(0, packetLength); ClientBuffer.RemoveRange(0, packetLength); Packet packet = new Packet(packetData.ToArray()); //do shit with packet data switch ((PuppyClientCodes)packet.OpCode) { case PuppyClientCodes.RequestTranslation: Task.Run(async delegate { string korean = packet.ReadString16(); string text = await checkTransExist(korean); Packet packet2 = new Packet((byte)PuppyServerCodes.TranslationResponse); packet2.WriteString16(korean); packet2.WriteString16(text); await SendAsync(packet2); Console.WriteLine("Translated: " + korean + " ***** " + text); }); break; case PuppyClientCodes.RequestEdit: Task.Run(async delegate { string korean = packet.ReadString16(); string englishToReplace = packet.ReadString16(); Server.translationDic.TryGetValue(korean, out string value); string fixedEnglish = await editExistingTranslation(korean, englishToReplace); Packet packet2 = new Packet((byte)PuppyServerCodes.EditResponse); packet2.WriteString16(korean); packet2.WriteString16(fixedEnglish); await SendAsync(packet2); Console.WriteLine("Edit Old: " + value + "."); Console.WriteLine("Edit Replaced:" + fixedEnglish); }); break; } } }
void Disconnect(object sender, RoutedEventArgs e) { EnableControlsForConnect(!clientSocket.Disconnect()); }
private async void Disconnect() { await clsock.ClientWork("Disconnect"); clsock.Disconnect(); }
/// <summary> /// Method to handle Login Requests /// </summary> /// <param name="Data">Packet in byte array</param> /// <param name="CSocket">Client Socket</param> public static void RequestLogin(byte[] Data, ClientSocket CSocket) { string AccountName = ""; string Password = ""; string ServerName = ""; if (Data.Length >= 276) { for (int i = 4; i < 0x114; i++) { if (i >= 0x14 && i < 0xf9) { if (Data[i] != 0x00) Password += Convert.ToChar(Data[i]); } if (i < 0x14) if (Data[i] != 0x00) AccountName += Convert.ToChar(Data[i]); if (i > 0xfa) if (Data[i] != 0x00) ServerName += Convert.ToChar(Data[i]); } } else { return; } System.Random Random = new System.Random(); Console.WriteLine("[LoginServer] " + AccountName + " logging in to " + ServerName); string DBPass = Database.Database.Password(AccountName); if (DBPass != "ERROR") { if (DBPass == Password) { //A ban Check could be put here uint Key = (uint)(Random.Next(10000000)); Key = Key << 32; Key = Key << 32; Key = (uint)(Key | (uint)Random.Next(10000000)); byte[] Key1 = new byte[4]; byte[] Key2 = new byte[4]; Key1[0] = (byte)(((ulong)Key & 0xff00000000000000L) >> 56); Key1[1] = (byte)((Key & 0xff000000000000) >> 48); Key1[2] = (byte)((Key & 0xff0000000000) >> 40); Key1[3] = (byte)((Key & 0xff00000000) >> 32); Key2[0] = (byte)((Key & 0xff000000) >> 24); Key2[1] = (byte)((Key & 0xff0000) >> 16); Key2[2] = (byte)((Key & 0xff00) >> 8); Key2[3] = (byte)(Key & 0xff); if (ServerName == "ghost") { if (AuthSocket.Authorize(AccountName, Key))//checks if the sending to the game server is successful (no error check atm so if it fails to send there will be an error) { CSocket.Send(Packets.AuthResponse("127.0.0.1", Key1, Key2)); } else { Console.WriteLine("Unable to send client data to gameserver"); CSocket.Send(Packets.ErrorMessage("Game Server is down")); Console.WriteLine("Disconnecting client"); CSocket.Disconnect(); } } else { Console.WriteLine("Client used the server name \"" + ServerName + "\" but this server is not on the connectable list"); Console.WriteLine("Disconnecting client"); CSocket.Disconnect(); } } //This has not been set for EO yet but is kept from the base source as it could be used in the future //This will set the Password for the account when it logs in for the first time to the password which is entered /*else if (DBPass == "") { Console.WriteLine("[LoginServer](Diagnostic) Set password for " + AccountName); Database.Database.SetPass(AccountName, Password); //OKAY to login! uint Key = (uint)(Random.Next(10000000) << 32); Key = Key << 32; Key = (uint)(Key | (uint)Random.Next(10000000)); byte[] Key1 = new byte[4]; byte[] Key2 = new byte[4]; Key1[0] = (byte)(((ulong)Key & 0xff00000000000000L) >> 56); Key1[1] = (byte)((Key & 0xff000000000000) >> 48); Key1[2] = (byte)((Key & 0xff0000000000) >> 40); Key1[3] = (byte)((Key & 0xff00000000) >> 32); Key2[0] = (byte)((Key & 0xff000000) >> 24); Key2[1] = (byte)((Key & 0xff0000) >> 16); Key2[2] = (byte)((Key & 0xff00) >> 8); Key2[3] = (byte)(Key & 0xff); if (ServerName == "ghost") { if (AuthSocket.Authorize(AccountName, Key, false))//checks if the sending to the game server is successful (no error check atm so if it fails to send there will be an error) { CSocket.Send(Packets.AuthResponse("127.0.0.1", Key1, Key2)); } else { Console.WriteLine("Unable to send client data to gameserver"); Console.WriteLine("Disconnecting client"); } } else { Console.WriteLine("Client used the server name \"" + ServerName + "\" but this server is not on the connectable list"); Console.WriteLine("Disconnecting client"); CSocket.Disconnect(); } }*/ else { Console.WriteLine("Client entered the wrong password"); CSocket.Send(Packets.WrongPass()); CSocket.Disconnect(); } } else { Console.WriteLine("DBPass equals ERROR: " + DBPass); CSocket.Disconnect(); } }
private void Application_Exit(object sender, EventArgs e) { CSocket.Disconnect(); CSocket.Dispose(); }
public void EndConnection() { ClientSocket.Disconnect(true); Connected = false; Console.WriteLine(">>> Connection closed <<<"); }
private void button2_Click(object sender, EventArgs e) { _mySock?.Disconnect("Ending connection"); }
/// <summary> /// Disconnect the client and performs any required cleanup tasks. /// </summary> public void Shutdown() { _socket.Disconnect("Shutting down"); }
private void Disconnect() { ClientSocket.Disconnect(true); NetworkState.RemoveClient(this); }
protected override int HandleCommand(BaseMessage message, ClientSocket client, ref List <BaseMessage> responses) { // Log if id is set if (Program.Settings.IsLog(message.Id)) { Console.WriteLine($"MPS {client}: {message}"); } // Update client echo client.ClientObject?.OnEcho(DateTime.UtcNow); // switch (message.Id) { case RT_MSG_TYPE.RT_MSG_CLIENT_HELLO: { responses.Add(new RT_MSG_SERVER_HELLO()); break; } case RT_MSG_TYPE.RT_MSG_CLIENT_CRYPTKEY_PUBLIC: { responses.Add(new RT_MSG_SERVER_CRYPTKEY_PEER() { Key = Utils.FromString(Program.KEY) }); break; } case RT_MSG_TYPE.RT_MSG_CLIENT_CONNECT_TCP: { var m00 = message as RT_MSG_CLIENT_CONNECT_TCP; client.SetToken(m00.AccessToken); responses.Add(new RT_MSG_SERVER_CONNECT_REQUIRE() { Contents = Utils.FromString("024802") }); break; } case RT_MSG_TYPE.RT_MSG_CLIENT_CONNECT_READY_REQUIRE: { responses.Add(new RT_MSG_SERVER_CRYPTKEY_GAME() { Key = Utils.FromString(Program.KEY) }); responses.Add(new RT_MSG_SERVER_CONNECT_ACCEPT_TCP() { UNK_00 = 0, UNK_01 = 0, UNK_02 = 0x01, UNK_06 = 0x01, IP = (client.RemoteEndPoint as IPEndPoint)?.Address }); break; } case RT_MSG_TYPE.RT_MSG_CLIENT_CONNECT_READY_TCP: { responses.Add(new RT_MSG_SERVER_CONNECT_COMPLETE() { ARG1 = 0x0001 }); break; } case RT_MSG_TYPE.RT_MSG_SERVER_ECHO: { client.ClientObject?.OnEcho(DateTime.UtcNow); break; } case RT_MSG_TYPE.RT_MSG_CLIENT_APP_TOSERVER: { var appMsg = (message as RT_MSG_CLIENT_APP_TOSERVER).AppMessage; switch (appMsg.Id) { case MediusAppPacketIds.MediusServerCreateGameWithAttributesResponse: { var msg = appMsg as MediusServerCreateGameWithAttributesResponse; int gameId = int.Parse(msg.MessageID.Split('-')[0]); int accountId = int.Parse(msg.MessageID.Split('-')[1]); string msgId = msg.MessageID.Split('-')[2]; var game = Program.GetGameById(gameId); var rClient = Program.GetClientByAccountId(accountId); game.DMEWorldId = msg.WorldID; rClient.AddLobbyMessage(new RT_MSG_SERVER_APP() { AppMessage = new MediusCreateGameResponse() { MessageID = msgId, StatusCode = MediusCallbackStatus.MediusSuccess, MediusWorldID = game.Id } }); break; } case MediusAppPacketIds.MediusServerJoinGameResponse: { var msg = appMsg as MediusServerJoinGameResponse; int gameId = int.Parse(msg.MessageID.Split('-')[0]); int accountId = int.Parse(msg.MessageID.Split('-')[1]); string msgId = msg.MessageID.Split('-')[2]; var game = Program.GetGameById(gameId); var rClient = Program.GetClientByAccountId(accountId); game.OnPlayerJoined(rClient); rClient.AddLobbyMessage(new RT_MSG_SERVER_APP() { AppMessage = new MediusJoinGameResponse() { MessageID = msgId, StatusCode = MediusCallbackStatus.MediusSuccess, GameHostType = game.GameHostType, ConnectInfo = new NetConnectionInfo() { AccessKey = msg.AccessKey, SessionKey = rClient.SessionKey, WorldID = game.DMEWorldId, ServerKey = msg.pubKey, AddressList = new NetAddressList() { AddressList = new NetAddress[MediusConstants.NET_ADDRESS_LIST_COUNT] { //new NetAddress() { Address = Program.SERVER_IP.ToString(), Port = (uint)Program.ProxyServer.Port, AddressType = NetAddressType.NetAddressTypeExternal}, #if FALSE new NetAddress() { Address = (client.RemoteEndPoint as IPEndPoint)?.Address.ToString(), Port = (uint)(client.Client as DMEObject).Port, AddressType = NetAddressType.NetAddressTypeExternal }, #else new NetAddress() { Address = (client.ClientObject as DMEObject).IP.ToString(), Port = (uint)(client.ClientObject as DMEObject).Port, AddressType = NetAddressType.NetAddressTypeExternal }, #endif new NetAddress() { AddressType = NetAddressType.NetAddressNone }, } }, Type = NetConnectionType.NetConnectionTypeClientServerTCPAuxUDP } } }); break; } case MediusAppPacketIds.MediusServerReport: { (client.ClientObject as DMEObject)?.OnWorldReport(appMsg as MediusServerReport); break; } case MediusAppPacketIds.MediusServerConnectNotification: { var msg = appMsg as MediusServerConnectNotification; Program.GetGameById((int)msg.MediusWorldUID)?.OnMediusServerConnectNotification(msg); break; } case MediusAppPacketIds.MediusServerEndGameResponse: { var msg = appMsg as MediusServerEndGameResponse; break; } default: { Console.WriteLine($"MPS Unhandled App Message: {appMsg.Id} {appMsg}"); break; } } break; } case RT_MSG_TYPE.RT_MSG_CLIENT_ECHO: { client.ClientObject?.OnEcho(DateTime.UtcNow); responses.Add(new RT_MSG_CLIENT_ECHO() { Value = (message as RT_MSG_CLIENT_ECHO).Value }); break; } case RT_MSG_TYPE.RT_MSG_CLIENT_DISCONNECT: case RT_MSG_TYPE.RT_MSG_CLIENT_DISCONNECT_WITH_REASON: { client.Disconnect(); break; } default: { Console.WriteLine($"MPS Unhandled Medius Command: {message.Id} {message}"); break; } } return(0); }