private Http2LoopbackConnection(SocketWrapper socket, Stream stream, TimeSpan timeout, bool transparentPingResponse) { _connectionSocket = socket; _connectionStream = stream; _timeout = timeout; _transparentPingResponse = transparentPingResponse; }
private void Communication_Begin(SocketWrapper socket) { var stop = false; while (!stop) { var command = socket.ReadString(); switch (command) { case Connection.STOP: stop = true; socket.Close(false); this.IsConnectionInProgress = false; break; case Connection.EXIT: stop = true; this.IsExiting = true; break; default: this.Execute(socket, command); break; } } }
protected override void Dispose(bool disposing) { // make sure we've unsubscribed from all session events and closed the channel // before we starting disposing base.Dispose(disposing); if (disposing) { if (_socket != null) { lock (_socketLock) { if (_socket != null) { _socket.Dispose(); _socket = null; } } } if (_channelOpen != null) { _channelOpen.Dispose(); _channelOpen = null; } if (_channelData != null) { _channelData.Dispose(); _channelData = null; } } }
internal Connection(ConnectionManager mgr, SocketWrapper sock) { _manager = mgr; _socket = sock; _state = ConnectionState.Connected; _receiveQueue = new Queue <byte[]>(); _socket.ConnectionError += SocketErrorHandler; _socket.SocketError += SocketNativeErrorHandler; _socket.Disconnected += SocketDisconnectHandler; _socket.Received += ReceiveDataHandler; _sendStream = new MemoryStream(); _connectionEvent = new ConnectionEventArgs(this); _connectionLostArgs = new ConnectionResultArgs(this, ConnectionResult.Unknown); _receiveArgs = new ConnectionReceiveArgs(this, null); CustomData = null; var threadStart = new ThreadStart(ConnectionThread); _connectionThread = new Thread(threadStart, 512 * 1024); }
/// <summary> /// Self Injects a new Socket. /// </summary> public HTTPRequestFactory3() { SocketWrapper theSocket = new SocketWrapper(); _socket = theSocket as ISocket; this.Setup(); }
internal void Shutdown() { _socket?.Remove(); var count = 2; if (_connectionThread != null) { _state = ConnectionState.Terminating; while (count-- > 0 && _state == ConnectionState.Terminating) { Thread.Sleep(10); } if (_state != ConnectionState.Terminated) { _connectionThread.Abort(); _connectionThread = null; _state = ConnectionState.Terminated; } } _manager.RemoveConnection(this); _socket = null; }
private static Task SendWrapper(SocketWrapper state, string data) { var requestAsBytes = Encoding.ASCII.GetBytes(data); state.socket.BeginSend(requestAsBytes, 0, requestAsBytes.Length, 0, WhenSent, state); return(Task.FromResult(state.sendDone.WaitOne())); }
public async Task <AsyncHandleResult> AddDatagramSocketAsync( ServiceSession session, UInt16 port ) { WFDSvcWrapperHandle socketHandle = null; Exception error = null; bool success = false; try { ThrowIfDisposed(); WiFiDirectTestLogger.Log( "AddDatagramSocketAsync... (port={0}) (Session={1})", port.ToString(), session.Handle ); SocketWrapper socket = await session.AddDatagramSocketListenerAsync(port); socketHandle = socket.Handle; success = true; } catch (Exception ex) { WiFiDirectTestLogger.Log("Exception in AddDatagramSocketAsync (this may be expected)"); error = ex; } return(new AsyncHandleResult(socketHandle, success, error)); }
public async Task <AsyncResult> SendMessageAsync( SocketWrapper socket, string message ) { Exception error = null; bool success = false; try { ThrowIfDisposed(); WiFiDirectTestLogger.Log( "SendMessageAsync... (Socket={0})", socket.Handle ); await socket.SendMessageAsync(message); socket.WaitForSend(); success = true; } catch (Exception ex) { WiFiDirectTestLogger.Log("Exception in SendMessageAsync (this may be expected)"); error = ex; } return(new AsyncResult(success, error)); }
private void ConnectSocket() { if (this._proxySocket == null) { var socket = new Socket(_remoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.Connect(_remoteEndPoint); if (this._isSecure) { Socket = new SocketWrapper(socket, this._certificate, this._uri); } else { Socket = new SocketWrapper(socket); } } else { var socket = this._proxySocket; var ca = new SocketAsyncEventArgs(); ca.RemoteEndPoint = _remoteEndPoint; ca.Completed += (sender, args) => { Socket = new SocketWrapper((Socket)sender); }; socket.ConnectAsync(ca); Thread.Sleep(2000); } }
private string Communication_SendPayload(SocketWrapper client, string request) { int sent = client.WriteString(request); var response = client.ReadString(); return(response); }
public static async Task <Http2LoopbackConnection> CreateAsync(SocketWrapper socket, Stream stream, Http2Options httpOptions, TimeSpan timeout) { if (httpOptions.UseSsl) { var sslStream = new SslStream(stream, false, delegate { return(true); }); using (X509Certificate2 cert = Configuration.Certificates.GetServerCertificate()) { #if !NETFRAMEWORK SslServerAuthenticationOptions options = new SslServerAuthenticationOptions(); options.EnabledSslProtocols = httpOptions.SslProtocols; var protocols = new List <SslApplicationProtocol>(); protocols.Add(SslApplicationProtocol.Http2); options.ApplicationProtocols = protocols; options.ServerCertificate = cert; options.ClientCertificateRequired = httpOptions.ClientCertificateRequired; await sslStream.AuthenticateAsServerAsync(options, CancellationToken.None).ConfigureAwait(false); #else await sslStream.AuthenticateAsServerAsync(cert, httpOptions.ClientCertificateRequired, httpOptions.SslProtocols, checkCertificateRevocation : false).ConfigureAwait(false); #endif } stream = sslStream; } var con = new Http2LoopbackConnection(socket, stream, timeout, httpOptions.EnableTransparentPingResponse); await con.ReadPrefixAsync().ConfigureAwait(false); return(con); }
private static async void StartAsyncClient(string host, int id) { var ipHostInfo = Dns.GetHostEntry(host.Split('/')[0]); var ipAddress = ipHostInfo.AddressList[0]; var remoteEndpoint = new IPEndPoint(ipAddress, Utils.PORT); var client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); var state = new SocketWrapper { socket = client, hostname = host.Split('/')[0], endpoint = host.Contains("/") ? host.Substring(host.IndexOf("/", StringComparison.Ordinal)) : "/", remoteEndPoint = remoteEndpoint, id = id }; await ConnectAsyncWrapper(state); string requestString = Utils.GetRequestString(state.hostname, state.endpoint); await SendAsyncWrapper(state, requestString); await ReceiveAsyncWrapper(state); Console.WriteLine("#{0}: Content length is:{1}", id, Utils.GetContentLength(state.responseContent.ToString())); client.Shutdown(SocketShutdown.Both); client.Close(); }
private static async Task SendAsyncWrapper(SocketWrapper state, string data) { var requestBytes = Encoding.ASCII.GetBytes(data); state.socket.BeginSend(requestBytes, 0, requestBytes.Length, 0, WhenSent, state); await Task.FromResult <object>(state.sendDone.WaitOne()); }
public void Sock_OnDisconnect(IPacketSend sender, bool willRetry) { socket.OnConnect -= Sock_OnConnect; socket.OnDisconnect -= Sock_OnDisconnect; socket.OnConnect -= Sock_OnConnect; socket = null; }
public LobbyMainWin() { InitializeComponent(); server = new SocketWrapper(); server.OnAccept += new SocketWrapper.dlgAccept(server_OnAccept); server.OnClose += new SocketWrapper.dlgClose(server_OnClose); server.OnRead += new SocketWrapper.dlgRead(PacketProcessor); Logger l = new Logger(tLog); //listClients.ItemsSource = clients; MapDB.Load("Data\\MapList.bin"); DigimonDB.Load("Data\\DigimonList.bin"); Opt = Settings.Deserialize(); Console.WriteLine("This server is configured to route players to the game server at {0}:{1}", Opt.GameServer.Host, Opt.GameServer.Port); if (Opt.LobbyServer.AutoStart) { server.Listen(new ServerInfo(Opt.LobbyServer.Port, Opt.LobbyServer.IP)); sbInfo1.Content = "Starting Lobby Server..."; } }
public static void PrintResponse(SocketWrapper state) { foreach (var i in state.responseContent.ToString().Split('\r', '\n')) { Console.WriteLine(i); } }
public async Task <Connection> EstablishConnectionAsync() { SocketWrapper closableWrapper = null; try { Stream stream = null; #if TARGET_BROWSER closableWrapper = new SocketWrapper(_listenSocket); stream = new WebSocketStream(_listenSocket, ownsSocket: true); #else var socket = await _listenSocket.AcceptAsync().ConfigureAwait(false); closableWrapper = new SocketWrapper(socket); try { socket.NoDelay = true; } // OSX can throw if socket is in weird state during close or cancellation catch (SocketException ex) when(ex.SocketErrorCode == SocketError.InvalidArgument && PlatformDetection.IsOSXLike) { } stream = new NetworkStream(socket, ownsSocket: false); #endif return(await Connection.CreateAsync(closableWrapper, stream, _options).ConfigureAwait(false)); } catch (Exception) { closableWrapper?.Close(); throw; } }
public void Sock_OnDisconnect(IPacketSend sender, bool willRetry) { gatewaySocket.OnConnect -= Sock_OnConnect; gatewaySocket.OnDisconnect -= Sock_OnDisconnect; gatewaySocket.OnConnect -= Sock_OnConnect; gatewaySocket = null; hasConnectedToGateway = false; }
private void OnListenSocketConnected(SocketWrapper sock) { Connection conn = CreateConnection(sock); conn.State = ConnectionState.Connected; OnConnected(conn); conn.StartConnectionProcessing(); }
public void AddSocket(SocketWrapper socket) { // Update UI to add this to list if (scenario5 != null) { scenario5.AddSocket(socket); } }
public void Send(string message, string user) { using (var socket = new SocketWrapper(Configuration.SERVER, 1012)) { var data = string.Format("SEND MESSAGE {0}:{1}:{2}\r\n", Configuration.UserIdentification, user, message); socket.Send(data); } }
public void Close() { if (socket != null && socket.IsConnected == true) { socket.Disconnect(); socket = null; } }
public async Task <AsyncStringResult> ReceiveMessageAsync( SocketWrapper socket ) { Exception error = null; bool success = false; string message = ""; try { ThrowIfDisposed(); WiFiDirectTestLogger.Log( "ReceiveMessageAsync... (Socket={0})", socket.Handle ); // TCP explicitly receives a message, UDP has a callback if (socket.IsTCP) { // Wait to receive a message for up to 20 seconds Task receiveMessageTask = socket.ReceiveMessageAsync(); if (receiveMessageTask == await Task.WhenAny(receiveMessageTask, Task.Delay(20000))) { WiFiDirectTestLogger.Log( "ReceiveMessageAsync DONE (Socket={0})", socket.Handle ); } else { throw new Exception("Timeout waiting for socket to receive message!"); } } socket.WaitForReceive(); if (!socket.HasReceivedMessages()) { throw new Exception("Did not actually receive message over socket!"); } while (socket.HasReceivedMessages()) { WiFiDirectTestLogger.Log("Reading message..."); message += socket.GetNextReceivedMessage(); } success = true; } catch (Exception ex) { WiFiDirectTestLogger.Log("Exception in SendMessageAsync (this may be expected)"); error = ex; } return(new AsyncStringResult(message, success, error)); }
private void SocketDisconnectHandler(SocketWrapper sock) { _state = ConnectionState.Disconnecting; lock (_receiveQueue) { _receiveQueue.Enqueue(null); _receiveQueue.Enqueue(new byte[0]); } }
public void Setup() { _endpoint = new IPEndPoint(IPAddress.Loopback, 45982); _client = new Socket(_endpoint.AddressFamily, SocketType.Stream, ProtocolType.IP); _wrapper = new SocketWrapper(_client); _wrapper.Bind(_endpoint); _wrapper.Listen(100); }
public override void Dispose() { _listenSocket = null; if (_socketWrapper != null) { _socketWrapper.Dispose(); _socketWrapper = null; } }
public Connection(SocketWrapper socket, Stream stream) { _socket = socket; _stream = stream; _readBuffer = new byte[BufferSize]; _readStart = 0; _readEnd = 0; }
private void OnNewSocketConnectFailed(SocketWrapper sock, SocketResultCode result) { var conn = GetConnection(sock); sock.Connected -= OnNewSocketConnected; sock.ConnectFailed -= OnNewSocketConnectFailed; OnConnectFailed(conn, Converter.SockResToConnRes(result)); conn.Shutdown(); }
static void Main(string[] args) { Mutex mutex = null; try { mutex = new Mutex(false, "3fb63999603824ebd0b416f74e96505023cfcd41"); if (mutex.WaitOne(0, false)) { Initialize(); BTWorker btWorker = new BTWorker(); MotusWorker motusWorker = new MotusWorker(); SocketWrapper tcpServer = new SocketWrapper(Configuration.server); tcpServer.StartServer(); while (true) { if (btWorker.GetState() == ThreadState.Stopped) { btWorker.Start(); } else if (btWorker.HasData()) { btWorker.GetData(_queue); } if (motusWorker.GetState() == ThreadState.Stopped) { motusWorker.Start(); } else if (motusWorker.HasData()) { motusWorker.GetData(_queue); } if (!_queue.IsEmpty()) { tcpServer.ServerSetTxData(_queue); } Thread.Sleep(4); } } } catch (Exception) { } finally { if (mutex != null) { mutex.Close(); mutex = null; } } }
public Connection(int connectionId, Manager manager, Socket client, IPEndPoint serverDestination) { _connectionId = connectionId; _manager = manager; Client = new SocketWrapper(client); _serverDestination = serverDestination; _packetProcessor = new PacketProcessor(_connectionId); Client.DataReceivedEvent += ClientOnDataReceivedEvent; Client.Receive(); }
public void Start() { if (!_started) { Console.WriteLine($"[{_connectionId}][Connection#Start]: Connecting..."); _started = true; Server = new SocketWrapper(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)); Server.Socket.BeginConnect(_serverDestination, DestinationConnectCallback, null); } else { Console.WriteLine($"[{_connectionId}][Connection#Start]: Already started."); } }
public void Setup() { _listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); _endpoint = new IPEndPoint(IPAddress.Loopback, 45982); _listener.Bind(_endpoint); _listener.Listen(10); _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); ThreadPool.QueueUserWorkItem(x => { Thread.Sleep(100); _client.Connect(_endpoint); }); _socket = _listener.Accept(); _wrapper = new SocketWrapper(_socket); }
// This will fire when the connected peer attempts to open a port for this connection // The peer should start a stream socket listener (for TCP) private async void OnRemotePortAdded(WiFiDirectServiceSession sender, WiFiDirectServiceRemotePortAddedEventArgs args) { try { ThrowIfDisposed(); var endpointPairCollection = args.EndpointPairs; var protocol = args.Protocol; if (endpointPairCollection.Count == 0) { manager.NotifyUser("No endpoint pairs for remote port added event", NotifyType.ErrorMessage); return; } manager.NotifyUser(String.Format("{0} Port {1} Added by remote peer", (protocol == WiFiDirectServiceIPProtocol.Tcp) ? "TCP" : ((protocol == WiFiDirectServiceIPProtocol.Udp) ? "UDP" : "???"), endpointPairCollection[0].RemoteServiceName ), NotifyType.StatusMessage ); SocketWrapper socketWrapper = null; if (args.Protocol == WiFiDirectServiceIPProtocol.Tcp) { // Connect to the stream socket listener StreamSocket streamSocket = new StreamSocket(); socketWrapper = new SocketWrapper(manager, streamSocket, null); manager.NotifyUser("Connecting to stream socket...", NotifyType.StatusMessage); await streamSocket.ConnectAsync(endpointPairCollection[0]); // Start receiving messages recursively var rcv = socketWrapper.ReceiveMessageAsync(); manager.NotifyUser("Stream socket connected", NotifyType.StatusMessage); } else if (args.Protocol == WiFiDirectServiceIPProtocol.Udp) { // Connect a socket over UDP DatagramSocket datagramSocket = new DatagramSocket(); socketWrapper = new SocketWrapper(manager, null, datagramSocket); manager.NotifyUser("Connecting to datagram socket...", NotifyType.StatusMessage); await datagramSocket.ConnectAsync(endpointPairCollection[0]); manager.NotifyUser("Datagram socket connected", NotifyType.StatusMessage); } else { manager.NotifyUser("Bad protocol for remote port added event", NotifyType.ErrorMessage); return; } socketList.Add(socketWrapper); // Update manager so UI can add to list manager.AddSocket(socketWrapper); } catch (Exception ex) { manager.NotifyUser("OnRemotePortAdded Failed: " + ex.Message, NotifyType.ErrorMessage); } }
public void AddStreamSocketInternal(StreamSocket socket) { SocketWrapper socketWrapper = new SocketWrapper(manager, socket, null); // Start receiving messages recursively var rcv = socketWrapper.ReceiveMessageAsync(); socketList.Add(socketWrapper); // Update manager so UI can add to list manager.AddSocket(socketWrapper); }
private void Button_Click_2(object sender, RoutedEventArgs e) { if (clientsRunning != 0) { return; } Interlocked.Increment(ref clientsRunning); // Client start for (int c = 0; c < Clients; c++) { if (c != 0) { Interlocked.Increment(ref clientsRunning); } _clientTasks[c] = new Task(() => { while (true) { SocketWrapper[] clientSocketArr = new SocketWrapper[1]; SocketsWrapper.Socket(AddressFamily.QCC_AF_INET, SocketType.QCC_SOCK_STREAM, clientSocketArr); using (SocketWrapper clientSocket = clientSocketArr[0]) { uint q = clientSocket.Connect(Address, Port); byte[] tempBytes = new byte[PatternLength]; int[] receivedArr = new int[1]; int bytesLeft = tempBytes.Length; int byteCount = 0; bool success = true; do { q = clientSocket.Recv(tempBytes, tempBytes.Length, receivedArr); if (q != 0) { success = false; break; } for (int i = 0; i < receivedArr[0]; i++) { if (tempBytes[i] != ((i + byteCount) % 256)) { success = false; break; } } byteCount += receivedArr[0]; bytesLeft -= receivedArr[0]; } while (bytesLeft > 0); // Update the count Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { if (success) { successCount.Text = (++_successCount).ToString(); } else { failCount.Text = (++_failCount).ToString(); } }); } } Interlocked.Decrement(ref clientsRunning); }); _clientTasks[c].Start(); } }
public async void AddDatagramSocketAsync(UInt16 port) { ThrowIfDisposed(); manager.NotifyUser("Adding stream socket listener for UDP port " + port, NotifyType.StatusMessage); var endpointPairCollection = session.GetConnectionEndpointPairs(); DatagramSocket socket = new DatagramSocket(); SocketWrapper socketWrapper = new SocketWrapper(manager, null, socket); socketList.Add(socketWrapper); // Bind UDP socket for receiving messages (peer should call connect and send messages to this socket) manager.NotifyUser("BindEndpointAsync...", NotifyType.StatusMessage); await socket.BindEndpointAsync(endpointPairCollection[0].LocalHostName, Convert.ToString(port, CultureInfo.InvariantCulture)); manager.NotifyUser("BindEndpointAsync Done", NotifyType.StatusMessage); manager.NotifyUser("AddDatagramSocketAsync...", NotifyType.StatusMessage); await session.AddDatagramSocketAsync(socket); manager.NotifyUser("AddDatagramSocketAsync Done", NotifyType.StatusMessage); // Update manager so UI can add to list manager.AddSocket(socketWrapper); }
public async void AddSocket(SocketWrapper socket) { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { lock (thisLock) { ConnectedSockets.Items.Add(socket); } }); }
private void Button_Click_1(object sender, RoutedEventArgs e) { if (serversRunning != 0) { return; } Interlocked.Increment(ref serversRunning); // Server start serverTaskMain = new Task(() => { // Server setup SocketWrapper[] listenSocketArr = new SocketWrapper[1]; uint q = SocketsWrapper.Socket(AddressFamily.QCC_AF_INET, SocketType.QCC_SOCK_STREAM, listenSocketArr); SocketWrapper listenSocket = listenSocketArr[0]; q = listenSocket.Bind("0.0.0.0", Port); q = listenSocket.Listen(10); for (int s = 0; s < Servers; s++) { if (s != 0) { Interlocked.Increment(ref serversRunning); } _serverTasks[s] = new Task(() => { string[] remoteAddr = new string[1]; int[] remotePort = new int[1]; SocketWrapper[] newSocketArr = new SocketWrapper[1]; while (listenSocket.Accept(remoteAddr, remotePort, newSocketArr) == 0) { int bytesLeft = PatternLength; int byteCount = 0; using (SocketWrapper newSocket = newSocketArr[0]) { int[] sentArr = new int[1]; while (bytesLeft != 0) { byte[] tempBytes = new byte[Math.Min(bytesLeft, MaxSendBuffer)]; for (int i = 0; i < tempBytes.Length; i++) { tempBytes[i] = (byte)((i + byteCount) % 256); } q = newSocket.Send(tempBytes, tempBytes.Length, sentArr); if (q != 0) { break; } byteCount += sentArr[0]; bytesLeft -= sentArr[0]; } } } Interlocked.Decrement(ref serversRunning); }); _serverTasks[s].Start(); } }); serverTaskMain.Start(); }