private void AcceptCallback(IAsyncResult ar) { Socket sock = ServerSocket.EndAccept(ar); ClientSockets.Add(sock); sock.BeginReceive(Buffer, 0, 100, SocketFlags.None, new AsyncCallback(ReceiveCallback), null); }
public void WaitData(EndPoint clientEndPoint) { if (!ClientSockets.ContainsKey(clientEndPoint)) { return; } TCPConnection client = ClientSockets[clientEndPoint]; if (!client.Socket.Connected) { return; } try { client.Socket.BeginReceive(client.ReceiveBuffer, 0, client.ReceiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), client); } catch (Exception ex) { //aqui es donde me da error constantemente OnException?.Invoke(ex); //Server Exception: An existing connection was forcibly closed by the remote host } }
protected override void OnSocketFatalDisconection(Exception e, Socket socket) { Console.WriteLine($"Client '{this[socket].Identifier}' has disconnected"); OnClientDisconnected(this[socket].Identifier); lock (this.LockObj) ClientSockets.Remove(this[socket]); }
public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); ClientSockets clientSockets = new ClientSockets(); clientSockets.Communicate(); }
private void ReceiveCallBack(IAsyncResult asyncResult) { //Socket socket = (Socket)asyncResult.AsyncState; TCPConnection client = (TCPConnection)asyncResult.AsyncState; if (!client.Socket.Connected) { return; } int receiveBytes = 0; try { receiveBytes = client.Socket.EndReceive(asyncResult); } catch (SocketException sex) { if (sex.SocketErrorCode == SocketError.ConnectionReset) { OnClientClose?.Invoke(client.Socket.RemoteEndPoint); ClientSockets.Remove(client.Socket.RemoteEndPoint); } else { OnException?.Invoke(sex); } } catch (Exception ex) { OnException?.Invoke(ex); return; } if (receiveBytes == 0) { return; } byte[] receiveBuffer = new byte[receiveBytes]; Array.Copy(client.ReceiveBuffer, receiveBuffer, receiveBytes); string receiveData = Encoding.ASCII.GetString(receiveBuffer); try { OnReceive?.Invoke(client.Socket.RemoteEndPoint, receiveData); } catch (Exception ex) { OnException?.Invoke(ex); } }
public void Stop() { IsRunning = false; //serverSocket.Shutdown(SocketShutdown.Both); foreach (KeyValuePair <EndPoint, TCPConnection> kvp in ClientSockets) { kvp.Value.Socket.Close(); } serverSocket.Close(); ClientSockets.Clear(); OnStop?.Invoke(); }
public override async void Dispose() { Working = false; await SendMsg(new MessageModel { IsDisConnected = true }); foreach (var clientSocket in ClientSockets) { clientSocket.Dispose(); } ClientSockets.Clear(); ClientSockets = null; Listener.ConnectionReceived -= OnConnection; Listener?.CancelIOAsync(); Listener.Dispose(); Listener = null; }
private async void OnConnection(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { Writer = null; ClientSockets.Add(args.Socket); var reader = new DataReader(args.Socket.InputStream); try { while (Working) { var sizeFaildCount = await reader.LoadAsync(sizeof(uint)); var stringLength = reader.ReadUInt32(); var actualStringLength = await reader.LoadAsync(stringLength); if (sizeFaildCount != sizeof(uint) || actualStringLength != stringLength) { reader.DetachStream(); reader.Dispose(); ClientSockets?.Remove(args.Socket); return; } var dataArrary = new byte[actualStringLength]; reader.ReadBytes(dataArrary); var dataJson = Encoding.UTF8.GetString(dataArrary); var data = JsonConvert.DeserializeObject <MessageModel>(dataJson); await SendMsg(data, args.Socket); MsgReceivedAction?.Invoke(data); } } catch (Exception e) { if (SocketError.GetStatus(e.HResult) == SocketErrorStatus.Unknown) { } Debug.WriteLine(string.Format("Received data: \"{0}\"", "Read stream failed with error: " + e.Message)); reader.DetachStream(); reader.Dispose(); ClientSockets?.Remove(args.Socket); } }
private void AcceptCallback(IAsyncResult ar) { Socket socket; try { socket = ServerSocket.EndAccept(ar); } catch (ObjectDisposedException) // I cannot seem to avoid this (on exit when properly closing sockets) { return; } ClientSockets.Add(socket); socket.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket); // Console.WriteLine("Client connected, waiting for request..."); ClientConnected?.Invoke(); ServerSocket.BeginAccept(AcceptCallback, null); }
// SUMMARY: On client connected protected virtual void AcceptCallback(IAsyncResult AR) { Socket socket = ServerSocket.EndAccept(AR); try { lock (this.LockObj) ClientSockets.Add(new SocketObject(socket)); Console.WriteLine("Client connected"); socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket); ServerSocket.BeginAccept(new AsyncCallback(AcceptCallback), null); this.OnClientConnected(this[socket].Identifier); } catch (Exception e) { this.OnClientDisconnected(this[socket].Identifier); lock (this.LockObj) OnSocketFatalDisconection(e, socket); } }
static void Main(string[] args) { var tasks = new List <Task <byte[]> >(); ClientSockets client = new ClientSockets(); var Hostname = "127.0.0.1"; var Port = 2055; Faker faker = new Faker(); Enumerable.Range(0, 5000).ToList().ForEach(f => { int dataLength = faker.Random.Int(1, 2048); byte[] data = faker.Random.Bytes(dataLength); List <byte> dataWithLength = new List <byte>(); dataWithLength.AddRange(BitConverter.GetBytes(dataLength)); dataWithLength.AddRange(data); tasks.Add(client.CallServer(dataWithLength.ToArray(), Hostname, Port)); }); tasks.ForEach(f => f.Wait()); Console.WriteLine("DONE"); Console.ReadKey(); }
private void ReceiveCallback(IAsyncResult ar) { Socket current = (Socket)ar.AsyncState; int received; try { received = current.EndReceive(ar); } catch (SocketException) { // Console.WriteLine("Client forcefully disconnected"); ClientForcefullyDisconnected?.Invoke(); // Don't shutdown because the socket may be disposed and its disconnected anyway. current.Close(); ClientSockets.Remove(current); return; } byte[] recBuf = new byte[received]; Array.Copy(Buffer, recBuf, received); string text = Encoding.ASCII.GetString(recBuf); // Console.WriteLine("Received Text: " + text); if (text.ToLower() == "") { ClientDisconnected?.Invoke(); return; } else { byte[] data = Encoding.ASCII.GetBytes("Received"); current.Send(data); TextReceived?.Invoke(text); } current.BeginReceive(Buffer, 0, BufferSize, SocketFlags.None, ReceiveCallback, current); }
private void AcceptCallback(IAsyncResult AR) { lock (lockAccept) { Socket socket; try { socket = ServerSocket.EndAccept(AR); var session = new SocketSession(socket, BufferSize); ClientSockets.Add(session); socket.BeginReceive(session.SessionStorage, 0, BufferSize, SocketFlags.None, ReceiveCallback, socket); ServerSocket.BeginAccept(AcceptCallback, null); } catch (Exception ex) // I cannot seem to avoid this (on exit when properly closing sockets) { LogController.WriteLog(new ServerLog("*** ERROR ***: \n" + ex.Message, ServerLogType.ERROR)); } } }
public void SendData(EndPoint clientEndPoint, string data) { responseData = data; if (!ClientSockets.ContainsKey(clientEndPoint)) { return; } if (data == "") { return; } //Socket socket = ClientSockets[clientEndPoint]; TCPConnection client = ClientSockets[clientEndPoint]; if (!client.Socket.Connected) { return; } //byte[] sendBufer = Encoding.ASCII.GetBytes(data); client.SendBufer = Encoding.ASCII.GetBytes(data); try { client.Socket.BeginSend(client.SendBufer, 0, client.SendBufer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), client); } catch (Exception ex) { OnException?.Invoke(ex); } }
private void AcceptCallBack(IAsyncResult asyncResult) { if (!IsRunning) { return; } TCPConnection client = new TCPConnection(); client.Socket = serverSocket.EndAccept(asyncResult); if (!client.Socket.Connected) { return; } ClientSockets.Add(client.Socket.RemoteEndPoint, client); OnClientConnected?.Invoke(client.Socket.RemoteEndPoint); serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), client); }
public void Start() { ClientSockets.Clear(); DeviceIds.Clear(); _wsServer?.Start(); }