public void Disconnect() { try { if (_connectedStatus != ClientStatusType.Disconnection && _connectedStatus != ClientStatusType.Disconnected) { _connectedStatus = ClientStatusType.Disconnection; CallChangeStatus(); if (_socket != null) { LingerOption lingerOption = new LingerOption(true, 1); _socket.LingerState = lingerOption; if (_socket.Connected) { _socket?.Shutdown(SocketShutdown.Both); _socket?.BeginDisconnect(false, DisconnectCallback, null); } } } } catch (Exception ex) { if (_showFail) { Debug.Fail(ex.Message, ex.StackTrace); } } finally { DisconnectFinalize(); } }
public static Task DisConnectTask(this Socket socket, bool reuse) => Task.Factory.FromAsync(socket.BeginDisconnect(reuse, null, null), socket.EndDisconnect);
/// <summary> /// 断开此SOCKET /// </summary> /// <param name="sock"></param> public void Disconnect(Socket sock) { sock.BeginDisconnect(false, AsynCallBackDisconnect, sock); }
public void StartClient() { IPAddress ip = IPAddress.Parse("192.168.56.1"); int port = 8080; IPEndPoint ipEnd = new IPEndPoint(ip, port); client.Connect(ipEnd); Socket handler = client.Client; string path; Console.Write("Would you like to send a file or a directory: "); if (Console.ReadLine().ToLower() == "file") { Console.Write("Choose a File to Send: "); path = Console.ReadLine(); while (!File.Exists(path)) { Console.Write("ERROR: File Entered Does not Exist on Selected Disk\nChoose a File to Send: "); path = Console.ReadLine(); } FileStream file = File.OpenRead(path); byte[] b = new byte[2048]; file.Read(b, 0, b.Length); string fileSend = Encoding.UTF8.GetString(b) + "$" + file.Name + "%%2"; b = Encoding.UTF8.GetBytes(fileSend); Console.Write("Sending File: " + file.Name + "... "); handler.BeginSend(b, 0, b.Length, 0, SendCallBack, new State(handler, b)); } else { Console.Write("Choose a Directory to Send: "); path = Console.ReadLine(); while (!Directory.Exists(path)) { Console.Write("ERROR: Directory Entered Does not Exist on Selected Disk\nChoose a Directory to Send: "); path = Console.ReadLine(); } DirectoryInfo directory = new DirectoryInfo(path); IEnumerator <FileInfo> files = directory.EnumerateFiles().GetEnumerator(); Console.WriteLine(directory.GetFiles().Length); while (files.MoveNext()) { mre.Reset(); FileInfo file = files.Current; Console.Write("Sending File: " + file.Name + "... "); byte[] b = new byte[file.Length]; file.OpenRead().Read(b, 0, b.Length); string fileSend = Encoding.UTF8.GetString(b) + "$" + file.Name + "%%2"; b = Encoding.UTF8.GetBytes(fileSend); handler.BeginSend(b, 0, b.Length, 0, SendCallBack, new State(handler, b)); mre.WaitOne(); } } handler.BeginDisconnect(false, DisconnectCallBack, handler); }
private static void OnReceive(IAsyncResult ar) { //if (!s_serverEngineStatus) { // return; //} try { // Casting the AsyncState to a socket class Socket receivedClientSocket = (Socket)ar.AsyncState; receivedClientSocket.EndReceive(ar); // Translating the array of received bytes to an intelligent class MessageStructure MessageStructure msgReceived = new MessageStructure(sr_byteMessage); // Constract the initial details of new object MessageStructure which will be sent out MessageStructure msgToSend = new MessageStructure { UserName = msgReceived.UserName, Command = msgReceived.Command, ClientName = msgReceived.ClientName, Color = msgReceived.Color }; // Create a new byte[] class which will filled in the following case switch statment byte[] messageBytes; switch (msgReceived.Command) { case Command.Register: msgToSend.Message = ServerDataEngine.Register(msgReceived.UserName, "Haven't logged in yet", "null", "Offline"); messageBytes = msgToSend.ToByte(); receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None); return; case Command.AttemptLogin: if (sr_clientList.Any(client => client.Name == msgReceived.ClientName)) { msgToSend.Message = "This Name already in use"; messageBytes = msgToSend.ToByte(); receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None); receivedClientSocket.Close(); return; } if (ServerDataEngine.CheckIfRegistered(msgReceived.UserName) == 0) { msgToSend.Message = "No user found which matches this User name"; messageBytes = msgToSend.ToByte(); receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None); receivedClientSocket.Close(); return; } if (ServerDataEngine.CheckStatus(msgReceived.UserName) == "Online") { msgToSend.Message = "This User Name already logged in"; messageBytes = msgToSend.ToByte(); receivedClientSocket.Send(messageBytes, 0, messageBytes.Length, SocketFlags.None); receivedClientSocket.Close(); return; } msgToSend.Command = Command.Login; msgReceived.Command = Command.Login; //messageBytes = msgToSend.ToByte(); //receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket); goto case Command.Login; case Command.Login: // When the Login Command is received the ServerNetworkEngine will // add that established connection (Socket) along // with the provoided information to distinguish it (Name) to sr_clientList // as a Client and sent the command Login to ohter clients to handle // it on their end excluding the sending client // and set the status of the new logged in client to online Client newClient = new Client { UserName = msgReceived.UserName, Name = msgReceived.ClientName, Socket = receivedClientSocket, Color = ColorTranslator.FromHtml(msgReceived.Color), IpEndPoint = receivedClientSocket.RemoteEndPoint as IPEndPoint }; // Adding the current handled established connection(client) to the connected _clientList sr_clientList.Add(newClient); // Setting the message to broadcast to all other clients msgToSend.Message = "<<< " + newClient.Name + " has joined the room >>>"; ServerDataEngine.UpdateStatus(msgReceived.UserName, msgReceived.ClientName, "Online"); ServerDataEngine.UpdateDate(msgReceived.UserName, Time.NowTimeDate()); if (ServerNetworkEngineEngineClientToAddEvent != null) { ServerNetworkEngineEngineClientToAddEvent.Invoke(newClient.Name, newClient.IpEndPoint); } break; case Command.Logout: // When the Logout Command is received the ServerNetworkEngine will // remove the the client from _clientList a long with all of // it's information, socket/clientName etc.. // server engine will also stop listening to the removed socket // and broadcast the message to all clients excluding the removed client receivedClientSocket.Shutdown(SocketShutdown.Both); receivedClientSocket.BeginDisconnect(true, (OnDisonnect), receivedClientSocket); // Setting the message to broadcast to all other clients msgToSend.Message = "<<< " + msgReceived.ClientName + " has just left the chat >>>"; // Removing client (established connection) _clientList foreach (Client client in sr_clientList.Where(client => client.Socket == receivedClientSocket)) { sr_clientList.Remove(client); ServerDataEngine.UpdateStatus(client.UserName, msgReceived.ClientName, "Offline"); break; } if (ServerNetworkEngineClientToRemoveEvent != null) { ServerNetworkEngineClientToRemoveEvent.Invoke(msgReceived.ClientName); } break; case Command.Disconnect: receivedClientSocket.BeginDisconnect(true, (OnDisonnect), receivedClientSocket); if (ServerNetworkEngineServerStopTickEvent != null) { ServerNetworkEngineServerStopTickEvent.Invoke(msgReceived.ClientName); } ServerDataEngine.UpdateStatus(msgReceived.UserName, msgReceived.ClientName, "Offline"); ++s_disconnectCout; if (sr_clientList.Count == s_disconnectCout) { if (ServerNetworkEngineServerStoppedEvent != null) { ServerNetworkEngineServerStoppedEvent.Invoke(); } ServerDataEngine.ResetStatus(); } break; case Command.List: // when the List command received serverEngine will send the names of all the // clients(established coneections) back to the requesting (client) (established connection) msgToSend.Command = Command.List; Client lastItem = sr_clientList[sr_clientList.Count - 1]; //msgToSend.ClientName = lastItem.Name; foreach (Client client in sr_clientList) { //To keep things simple we use a marker to separate the user names msgToSend.Message += client.Name + ","; } // Convert msgToSend to a bytearray representative, this is needed in order to send(broadcat) the message over the TCP protocol messageBytes = msgToSend.ToByte(); // Send(broadcast) the name of the estalished connections(cleints) in the chat receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket); break; case Command.Message: // Set the message which will be broadcasted to all the connected clients ServerDataEngine.AddMessage(msgReceived.UserName, msgReceived.Message, Time.NowTimeDate(), "false", "null"); msgToSend.Message = msgReceived.Message; if (ServerNetworkEngineSendPublicMessageEvent != null) { ServerNetworkEngineSendPublicMessageEvent.Invoke(msgToSend.ClientName, ColorTranslator.FromHtml(msgReceived.Color), msgToSend.Message); } break; case Command.NameChange: foreach (Client client in sr_clientList.Where(client => client.Name == msgReceived.ClientName)) { client.Name = msgReceived.Message; break; } msgToSend.Message = msgReceived.Message; if (ServerNetworkEngineClientNameChangedEvent != null) { ServerNetworkEngineClientNameChangedEvent.Invoke(msgReceived.ClientName, msgReceived.Message); } ServerDataEngine.UpdateLoggedLastLogged(msgReceived.ClientName, msgReceived.Message); goto case Command.ColorChanged; case Command.ColorChanged: Color newColor = ColorTranslator.FromHtml(msgToSend.Color); foreach (Client client in sr_clientList.Where(client => client.Name == msgReceived.ClientName)) { client.Color = newColor; break; } msgToSend.Message = msgReceived.Message; if (ServerNetworkEngineClientColorChangedEvent != null) { ServerNetworkEngineClientColorChangedEvent.Invoke(msgReceived.ClientName, newColor); } break; case Command.PrivateStart: foreach (Client client in sr_clientList.Where(client => client.Name == msgReceived.Private)) { msgToSend.Private = msgReceived.Private; messageBytes = msgToSend.ToByte(); client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket); if (ServerNetworkEnginePrivateChatStartedEvent != null) { ServerNetworkEnginePrivateChatStartedEvent.Invoke(msgReceived.ClientName, msgReceived.Private); } break; } break; case Command.PrivateMessage: foreach (Client client in sr_clientList.Where(clientLinq => clientLinq.Name == msgReceived.Private)) { msgToSend.Private = msgReceived.Private; msgToSend.Message = msgReceived.Message; messageBytes = msgToSend.ToByte(); client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket); receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket); if (ServerNetworkEnginePrivateChatMessageEvent != null) { ServerNetworkEnginePrivateChatMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Private, msgReceived.Message); } ServerDataEngine.AddMessage(msgReceived.UserName, msgReceived.Message, Time.NowTimeDate(), client.UserName, "null"); break; } break; case Command.PrivateStopped: foreach (Client client in sr_clientList.Where(clientLinq => clientLinq.Name == msgReceived.Private)) { msgToSend.Private = msgReceived.Private; messageBytes = msgToSend.ToByte(); client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket); receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket); } if (ServerNetworkEnginePrivateChatStoppedEvent != null) { ServerNetworkEnginePrivateChatStoppedEvent.Invoke(msgReceived.ClientName, msgReceived.Private); } break; case Command.ImageMessage: MemoryStream s_ms = new MemoryStream(msgReceived.ImgByte); Image s_img = Image.FromStream(s_ms); if (!Directory.Exists(@"Images\" + msgReceived.UserName)) { Directory.CreateDirectory(@"Images\" + msgReceived.UserName); } if (msgReceived.Private != null) { if (ServerNetworkEngineImageMessageEvent != null) { ServerNetworkEngineImageMessageEvent.Invoke(s_img, msgReceived.ClientName, msgReceived.Private); } Task.Factory.StartNew(() => { foreach (Client client in sr_clientList.Where(clientLinq => clientLinq.Name == msgReceived.Private)) { msgToSend.Private = msgReceived.Private; msgToSend.ImgByte = msgReceived.ImgByte; messageBytes = msgToSend.ToByte(); client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket); receivedClientSocket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, receivedClientSocket); ServerDataEngine.AddMessage(msgReceived.UserName, "null", Time.NowTimeDate(), client.UserName, @"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate() + @"-" + client.UserName); //s_img.Save(@"Images\" + msgReceived.Private + @"\" + Time.SaveTimeDate() + client.UserName + @".png"); s_img.Save(@"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate() + @".png"); break; } }); break; } if (ServerNetworkEngineImageMessageEvent != null) { ServerNetworkEngineImageMessageEvent.Invoke(s_img, msgReceived.ClientName, msgReceived.Private); } msgToSend.ImgByte = msgReceived.ImgByte; messageBytes = msgToSend.ToByte(); Task.Factory.StartNew(() => { foreach (Client client in sr_clientList) { client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket); ServerDataEngine.AddMessage(msgReceived.UserName, "null", Time.NowTimeDate(), "false", @"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate()); s_img.Save(@"Images\" + msgReceived.UserName + @"\" + Time.SaveTimeDate() + @".png"); } }); break; } // Send(broadcast) the message to clients (established connections) Task.Factory.StartNew(() => { if (msgToSend.Command != Command.List && msgToSend.Command != Command.PrivateStart && msgToSend.Command != Command.PrivateMessage && msgToSend.Command != Command.PrivateStopped && msgToSend.Command != Command.Disconnect && msgToSend.Command != Command.ImageMessage) { messageBytes = msgToSend.ToByte(); foreach (Client client in sr_clientList) { //if (client.Socket != receivedClientSocket || msgToSend.Command != Command.Login) { client.Socket.BeginSend(messageBytes, 0, messageBytes.Length, SocketFlags.None, OnSend, client.Socket); //} } } }); // Continue listneing to receivedClientSocket established connection(client) if (msgReceived.Command != Command.Logout && msgReceived.Command != Command.Disconnect && msgReceived.Command != Command.AttemptLogin && msgReceived.Command != Command.Register) { receivedClientSocket.BeginReceive(sr_byteMessage, 0, sr_byteMessage.Length, SocketFlags.None, OnReceive, receivedClientSocket); } } catch (Exception ex) { MessageBox.Show(ex.Message + @" -> OnReceive", @"Server", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void BeginDisconnect_Success() { AutoResetEvent completed = new AutoResetEvent(false); IPEndPoint loopback = new IPEndPoint(IPAddress.Loopback, 0); using (var server1 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback)) using (var server2 = SocketTestServer.SocketTestServerFactory(SocketImplementationType.Async, loopback)) { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnCompleted; args.UserToken = completed; args.RemoteEndPoint = server1.EndPoint; using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.True(client.ConnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); client.EndDisconnect(client.BeginDisconnect(true, null, null)); args.RemoteEndPoint = server2.EndPoint; Assert.True(client.ConnectAsync(args)); completed.WaitOne(); Assert.Equal(SocketError.Success, args.SocketError); } } }
public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state) { return(m_ClientSocket.BeginDisconnect(reuseSocket, callback, state)); }
private void Button2_Click(object sender, EventArgs e) { socket.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), null); }
public void Close() { socket.Shutdown(SocketShutdown.Both); socket.BeginDisconnect(true, new AsyncCallback(DisconnectCallback), socket); }
/// <summary> /// Disconnect from the server /// </summary> public void Disconnect() { _socket.BeginDisconnect(false, DisconnectCallback, null); }
/// <summary> /// Method used to gracefully disconnect from the server. /// </summary> /// <param name="socket"></param> public static void Disconnect(Socket socket) { socket.BeginDisconnect(false, DisconnectCallback, socket); }
public void Disconnect() { _reading = false; _twitchSocket.BeginDisconnect(true, DisconnectCallback, null); }
public IAsyncResult BeginDisconnect(bool reuseSocket, AsyncCallback callback, object state) { var connState = new Tuple <Socket, bool>(m_Socket, m_Socket.IsConnected()); return(m_Socket.BeginDisconnect(reuseSocket, callback, new RedisAsyncStateWrapper(state, connState))); }
private static void OnReceive(IAsyncResult ar) { if (!Status) { return; } try { // Let the server know the message was recieved s_socket.EndReceive(ar); // Convert message from bytes to messageStracure class and store it in msgReceieved MessageStructure msgReceived = new MessageStructure(s_byteMessage); // Set new bytes and start recieving again s_byteMessage = new byte[2097152]; if (msgReceived.Command == Command.Disconnect) { Status = false; MessageStructure msgToSend = new MessageStructure { Command = Command.Disconnect, ClientName = Client.Name, UserName = Client.UserName }; byte[] b = msgToSend.ToByte(); s_socket.Send(b, 0, b.Length, SocketFlags.None); s_socket.Shutdown(SocketShutdown.Both); s_socket.BeginDisconnect(true, (OnDisonnect), s_socket); if (ClientNetworkEngineDisconnectEvent != null) { ClientNetworkEngineDisconnectEvent.Invoke(); } return; } if (msgReceived.Command != Command.AttemptLogin && msgReceived.Command != Command.Register) { s_socket.BeginReceive(s_byteMessage, 0, s_byteMessage.Length, SocketFlags.None, OnReceive, s_socket); } switch (msgReceived.Command) { case Command.Register: if (ClientNetworkEngineRegisterMessageEvent != null) { ClientNetworkEngineRegisterMessageEvent.Invoke(msgReceived.Message); } break; case Command.AttemptLogin: if (ClientNetworkEngineAttemptLoginErrorEvent != null) { ClientNetworkEngineAttemptLoginErrorEvent.Invoke(msgReceived.Message); } break; case Command.Login: if (msgReceived.ClientName == Client.Name) { if (ClientNetworkEngineLoggedinEvent != null) { ClientNetworkEngineLoggedinEvent.Invoke(); } // Send Request for online client list MessageStructure msgToSend = new MessageStructure { Command = Command.List, ClientName = Client.Name }; byte[] byteMessageToSend = msgToSend.ToByte(); s_socket.BeginSend(byteMessageToSend, 0, byteMessageToSend.Length, SocketFlags.None, OnSend, s_socket); return; } if (ClientNetworkEngineLoginEvent != null) { ClientNetworkEngineLoginEvent.Invoke(msgReceived.ClientName, msgReceived.Message); } break; case Command.List: if (ClientNetworkEngineClientsListEvent != null) { ClientNetworkEngineClientsListEvent.Invoke(msgReceived.Message); } break; case Command.Logout: if (ClientNetworkEngineLogoutEvent != null) { ClientNetworkEngineLogoutEvent.Invoke(msgReceived.ClientName, msgReceived.Message); } break; case Command.Message: if (ClientNetworkEngineMessageEvent != null) { ClientNetworkEngineMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Message, ColorTranslator.FromHtml(msgReceived.Color)); } break; case Command.NameChange: if (Client.Name == msgReceived.ClientName) { Client.Name = msgReceived.Message; } if (ClientNetworkEngineNameChangeEvent != null) { ClientNetworkEngineNameChangeEvent.Invoke(msgReceived.ClientName, msgReceived.Message, ColorTranslator.FromHtml(msgReceived.Color)); } break; case Command.ColorChanged: if (ClientNetworkEngineColorChangedEvent != null) { ClientNetworkEngineColorChangedEvent.Invoke(msgReceived.ClientName, ColorTranslator.FromHtml(msgReceived.Color)); } break; case Command.PrivateStart: if (ClientNetworkEnginePrivateChatStartEvent != null) { ClientNetworkEnginePrivateChatStartEvent.Invoke(msgReceived.ClientName); } break; case Command.PrivateMessage: if (ClientNetworkEnginePrivateMessageEvent != null) { ClientNetworkEnginePrivateMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Private, msgReceived.Message); } break; case Command.PrivateStopped: if (ClientNetworkEnginePrivateStoppedEvent != null) { ClientNetworkEnginePrivateStoppedEvent.Invoke(msgReceived.ClientName); } //TabPagePrivateChatReceiveClientEvent.Invoke(msgReceived.ClientName, msgReceived.Private, msgReceived.Message, 1); break; case Command.ServerMessage: if (ClientNetworkEngineServerMessageEvent != null) { ClientNetworkEngineServerMessageEvent.Invoke(msgReceived.Message); } break; case Command.ImageMessage: MemoryStream ms = new MemoryStream(msgReceived.ImgByte); Image img = Image.FromStream(ms); if (ClientNetworkEngineImageMessageEvent != null) { ClientNetworkEngineImageMessageEvent.Invoke(msgReceived.ClientName, msgReceived.Private, img); } break; } } //catch (ArgumentException) //{ // //MessageBox.Show(ex.Message + @" -> OnReceive", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error); //} catch (Exception ex) { MessageBox.Show(ex.Message + @" -> OnReceive", @"Chat: " + Client.Name, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public void Close() { clientSocket.BeginDisconnect(false, new AsyncCallback(DisconnectCallBack), clientSocket); }
public void Disconnect() { socket.BeginDisconnect(true, OnDisconnectComplete(), null); return; }
private static void Disconnect() { Socket?.BeginDisconnect(false, OnEndHostComplete, Socket); }
private void StartDisconnect() { _socket.BeginDisconnect(false, DisconnectCallback, null); }
public override Task DisconnectAsync(Socket s, bool reuseSocket) => Task.Factory.FromAsync( (callback, state) => s.BeginDisconnect(reuseSocket, callback, state), s.EndDisconnect, null);
public void BeginDisconnect() { object[] DisconnectState = { ConnectSocket }; ConnectSocket?.BeginDisconnect(true, DisconnectCallBack, DisconnectState); }
public void Disconnect() { m_stopSignal = true; m_socket.BeginDisconnect(true, new AsyncCallback(_onBeginDisconnect), m_socket); }
public void BeginDisconnect_NonWindows_NotSupported() { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { Assert.Throws<PlatformNotSupportedException>(() => client.BeginDisconnect(true, null, null)); } }
public void Disconnect() { clientSocket.BeginDisconnect(false, new AsyncCallback(DisconnectCallback), this); Dispose(); }