IEnumerator ConnectInternal(bool useDelay) { if (useDelay) { yield return(new WaitForSeconds(5f)); // немного ждём, полезно для реконнекта } if (startConnect) { yield break; } startConnect = true; if (socket == null) { socket = new TcpSocket(); socket.OnMessageReceived += OnMessageReceived; socket.OnError += OnErrorReceived; } var connectInfo = ChatSettings.Me; socket.Connect(connectInfo.Host, connectInfo.Port); textEntering.gameObject.SetActive(true); buttonConnect.gameObject.SetActive(false); //chatTitle.gameObject.SetActive(false); startConnect = false; ++connectCounter; yield break; }
public TrackerGetHttpEntry Find(TcpSocket socket) { TrackerGetHttpEntry entry; items.TryGetValue(socket, out entry); return(entry); }
public async Task SendAsyncShouldTimeoutMultipleMessagesAtATime() { var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) using (var socket = new TcpSocket(endpoint, log: TestConfig.InfoLog)) using (var conn = new Connection(socket, new ConnectionConfiguration(requestTimeout: TimeSpan.FromMilliseconds(100)), log: TestConfig.InfoLog)) { server.HasClientConnected.Wait(TimeSpan.FromSeconds(3)); Assert.That(server.ConnectionEventcount, Is.EqualTo(1)); var tasks = new[] { conn.SendAsync(new MetadataRequest(), CancellationToken.None), conn.SendAsync(new MetadataRequest(), CancellationToken.None), conn.SendAsync(new MetadataRequest(), CancellationToken.None) }; await TaskTest.WaitFor(() => tasks.All(t => t.IsFaulted)); foreach (var task in tasks) { Assert.That(task.IsFaulted, Is.True, "Task should have faulted."); Assert.That(task.Exception.InnerException, Is.TypeOf <TimeoutException>(), "Task fault has wrong type."); } } }
public async Task CanObtainAcceptedRemoteEndpointUsingTasks() { using (CompletionThread worker = new CompletionThread()) { IPEndPoint endpoint; SocketFactory factory = new SocketFactory(worker); using (TcpSocket server = factory.Tcp()) using (TcpSocket client = factory.Tcp()) { worker.Start(); client.Bind(); server.Bind(IPAddress.Loopback); server.Listen(1); endpoint = server.Info().Endpoint; Task <TcpSocketAccept> accepting = server.Accept(); await client.Connect(endpoint); TcpSocketAccept accepted = await accepting; IPEndPoint remote = accepted.GetRemote(); Assert.That(remote.Address, Is.EqualTo(endpoint.Address)); Assert.That(remote.Port, Is.Not.EqualTo(endpoint.Port)); Assert.That(remote.Port, Is.Not.Zero); } } }
public static void Receive(TcpSocket socket, StreamSocket client, ReceiveState receiveState, Action <byte[], int> onReceived) { client.InputStream.ReadAsync(receiveState.buffer.AsBuffer(0, 4), 4u, InputStreamOptions.Partial).Completed = (IAsyncOperationWithProgress <IBuffer, uint> numBytesOp, AsyncStatus numBytesStatus) => { var numBytes = BitConverter.ToInt32(numBytesOp.GetResults().ToArray(), 0); #if HOLOLENSSOCKET_DEBUG Debug.Log("Expecting " + numBytes.ToString() + " bytes."); #endif while (receiveState.buffer.Length < numBytes) { socket.ResizeReceiveBuffer(2); } client.InputStream.ReadAsync(receiveState.buffer.AsBuffer(0, numBytes), (uint)numBytes, InputStreamOptions.Partial).Completed = (IAsyncOperationWithProgress <IBuffer, uint> bytesOp, AsyncStatus bytesStatus) => { if (onReceived != null) { #if HOLOLENSSOCKET_DEBUG Debug.Log("Received " + bytesOp.GetResults().Length + " bytes."); #endif onReceived(receiveState.buffer, receiveState.buffer.Length); } }; }; }
public async Task <string> Send(IPEndPoint endpoint, string message) { int progress = 0; byte[] output = new byte[message.Length]; byte[] bytes = Encoding.ASCII.GetBytes(message); using (TcpSocket socket = factory.Tcp()) { socket.Bind(); TcpSocketConnect connected = await socket.Connect(endpoint); TcpSocketSend sent = await socket.Send(bytes); while (progress < output.Length) { SocketBuffer buffer = new SocketBuffer(output, progress); TcpSocketReceive received = await socket.Receive(buffer); if (received.Count == 0) { break; } progress += received.Count; } } return(Encoding.ASCII.GetString(output)); }
/// <summary> /// Handle the disconnection of a client. /// </summary> /// <param name="aSocket">The socket fo the client now disconnected.</param> private static void DisconnectionHandler(TcpSocket aSocket) { try { if (aSocket != null && aSocket.Wrapper != null) { Client client = aSocket.Wrapper as Client; if (client.Account != null) { sLogger.Info("Disconnection of {0}, with {1}.", aSocket.IPAddress, client.Account); } client.Disconnect(); client.Dispose(); aSocket.Wrapper = null; } else if (aSocket != null) { aSocket.Disconnect(); } } catch (Exception exc) { sLogger.Error(exc); } }
public HttpAdapter(string srv, int port, TcpSocket socket, TunInterface tun) : base(socket, tun) { server = srv; this.port = port; Init(); }
public Player(TcpSocket tcpSocket) { Name = ""; IsReady = false; IsGameLoaded = false; clientSocket = tcpSocket; }
private static Client CreatedConnectedClient() { var client = new TcpSocket(); client.Connect(ServerAddress, serverPort); return(client); }
public void RejectHugePacket() { using (TcpListener listener = new TcpListener(1024)) { listener.Blocking = true; listener.Listen(PORT); TcpSocket clientSock = new TcpSocket(); var connectionResult = clientSock.ConnectAsync("localhost", PORT).Result; var status = listener.Accept(out TcpSocket serverSock); Assert.AreEqual(SocketStatus.Done, status); var largePacket = new NetPacket(); largePacket.WriteBytes(new byte[8192], true); while (clientSock.Send(largePacket) != SocketStatus.Done) { ; } Assert.AreEqual(SocketStatus.Disconnected, serverSock.Receive(largePacket)); Assert.IsFalse(serverSock.Connected); clientSock.Dispose(); serverSock.Dispose(); largePacket.Dispose(); } }
public override void init() { try { io = new IO(); if (lport == -1) { Type c = Type.GetType(target); IForwardedTCPIPDaemon daemon = (IForwardedTCPIPDaemon)Activator.CreateInstance(c); daemon.setChannel(this); Object[] foo = getPort(session, rport); daemon.setArg((Object[])foo[3]); new ThreadAux(daemon).start(); connected = true; return; } else { TcpSocket socket = (factory == null) ? new TcpSocket(target, lport) : factory.createSocket(target, lport); socket.setTcpNoDelay(true); io.setInputStream(socket.getInputStream()); io.setOutputStream(socket.getOutputStream()); connected = true; } } catch (Exception e) { Console.WriteLine("target={0},port={1}", target, lport); Console.WriteLine(e); } }
public void StartSend(IPAddress Address, int Port, string FilePath) { // store the path _filePath = FilePath; // start listening on the port _clientSocket = new TcpSocket(); // use the DataReceived callback _clientSocket.DataReceived += new TcpSocket.DataReceivedDelegate(OnDataReceived); _clientSocket.Connected += new TcpSocket.ConnectedDelegate(OnConnected); // non blocking listen _clientSocket.ListenAsync(Address, Port); if (!_clientSocket.IsConnected) { // connect attempt failed throw new CryptoSocketException("DtmFileTransfer:BeginSendFile", "Could not connect to the remote host!", new SocketException((int)SocketError.ConnectionAborted)); } else { // connection established _clientSocket.ReceiveBufferSize = m_bufferSize; _clientSocket.SendBufferSize = m_bufferSize; _isConnected = true; } }
public TcpSocketAccept(SocketStatus status, TcpSocket socket, TcpSocket connection, TcpSocketAcceptParse parse) { this.status = status; this.socket = socket; this.connection = connection; this.parse = parse; }
// Use this for initialization void Awake() { clientSocket = new TcpSocket("127.0.0.1", 54000); clientSocket.MessageReceived += ClientSocket_MessageReceived; // Putting the character localPosition in a vector so we can manipulate its localPosition later on playerCharacter = GameObject.Find("PlayerCharacter").transform; characterVector = playerCharacter.position; // Initializing vectors that will be changed through coordinates we'll be receiving #region gameobjectVectors initialization gameobjectVectors[0] = Vector3.zero; //0 - head gameobjectVectors[1] = Vector3.zero; //1 - shoulderSpine gameobjectVectors[2] = Vector3.zero; //2 - leftShoulder gameobjectVectors[3] = Vector3.zero; //3 - leftElbow gameobjectVectors[4] = Vector3.zero; //4 - leftHand gameobjectVectors[5] = Vector3.zero; //5 - rightShoulder gameobjectVectors[6] = Vector3.zero; //6 - rightElbow gameobjectVectors[7] = Vector3.zero; //7 - rightHand gameobjectVectors[8] = Vector3.zero; //8 - midSpine gameobjectVectors[9] = Vector3.zero; //9 - baseSpine gameobjectVectors[10] = Vector3.zero; //10 - leftHip gameobjectVectors[11] = Vector3.zero; //11 - leftKnee gameobjectVectors[12] = Vector3.zero; //12 - leftFoot gameobjectVectors[13] = Vector3.zero; //13 - rightHip gameobjectVectors[14] = Vector3.zero; //14 - rightKnee gameobjectVectors[15] = Vector3.zero; //15 - rightFoot gameobjectVectors[16] = Vector3.zero; //16 - leftWrist gameobjectVectors[17] = Vector3.zero; //17 - rightWrist gameobjectVectors[18] = Vector3.zero; //18 - neck #endregion // For using VR as Z buffer offset //startingPosX = characterVector.x; //startingPosZ = characterVector.z; }
public TcpSocketReceive(SocketStatus status, int count, TcpSocket socket, SocketBuffer buffer) { this.status = status; this.count = count; this.socket = socket; this.buffer = buffer; }
public async Task ReadShouldIgnoreMessageWithUnknownCorrelationId() { const int correlationId = 99; var receivedData = false; var mockLog = new MemoryLog(); var config = new ConnectionConfiguration(onRead: (e, buffer, elapsed) => receivedData = true); var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) using (var socket = new TcpSocket(endpoint, config, mockLog)) using (var conn = new Connection(socket, config, log: mockLog)) { //send correlation message server.SendDataAsync(CreateCorrelationMessage(correlationId)).Wait(TimeSpan.FromSeconds(5)); //wait for connection await TaskTest.WaitFor(() => server.ConnectionEventcount > 0); Assert.That(server.ConnectionEventcount, Is.EqualTo(1)); await TaskTest.WaitFor(() => receivedData); // shortly after receivedData, but still after await TaskTest.WaitFor(() => mockLog.LogEvents.Any(e => e.Item1 == LogLevel.Warn && e.Item2.Message == $"Unexpected response from {endpoint} with correlation id {correlationId} (not in request queue).")); } }
public void TestEvent() { bool isOnConnecting = false; bool isOnConnected = false; bool isOnDisconnected = false; bool isOnSend = false; bool isOnReceive = false; TcpSocket tcp = new TcpSocket(); tcp.OnConnecting += () => { isOnConnecting = true; }; tcp.OnConnected += () => { isOnConnected = true; }; tcp.OnDisconnected += () => { isOnDisconnected = true; }; tcp.OnSendBytes += (x) => { isOnSend = true; }; tcp.OnReceiveBytes += (x) => { isOnReceive = true; }; tcp.Connect(Common.GetIpEndPoint()); Assert.IsTrue(isOnConnecting); Common.WaitTrue(ref isOnConnected); Assert.IsTrue(isOnConnected); tcp.Send(new byte[10]); Common.WaitTrue(ref isOnSend); Assert.IsTrue(isOnSend); Common.WaitTrue(ref isOnReceive); Assert.IsTrue(isOnReceive); tcp.Disconnect(); Assert.IsTrue(isOnDisconnected); }
public async Task SendAsyncShouldNotAllowResponseToTimeoutWhileAwaitingKafkaToEstableConnection() { var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var socket = new TcpSocket(endpoint, log: TestConfig.InfoLog)) using (var conn = new Connection(socket, new ConnectionConfiguration(requestTimeout: TimeSpan.FromSeconds(1000)), log: TestConfig.InfoLog)) { Console.WriteLine("SendAsync blocked by reconnection attempts..."); var taskResult = conn.SendAsync(new MetadataRequest(), CancellationToken.None); Console.WriteLine("Task result should be WaitingForActivation..."); Assert.That(taskResult.IsFaulted, Is.False); Assert.That(taskResult.Status, Is.EqualTo(TaskStatus.WaitingForActivation)); Console.WriteLine("Starting server to establish connection..."); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) { server.OnClientConnected += () => Console.WriteLine("Client connected..."); server.OnBytesReceived += b => { var request = KafkaDecoder.DecodeHeader(b); AsyncContext.Run(async() => await server.SendDataAsync(MessageHelper.CreateMetadataResponse(request.CorrelationId, "Test"))); }; await Task.WhenAny(taskResult, Task.Delay(TimeSpan.FromSeconds(10))); Assert.That(taskResult.IsFaulted, Is.False); Assert.That(taskResult.IsCanceled, Is.False); await taskResult; Assert.That(taskResult.Status, Is.EqualTo(TaskStatus.RanToCompletion)); } } }
protected virtual void Dispose(bool disposing) { if (disposed) { return; } Task.Run(async() => { // delay calling tcp connection close() // so that server have enough time to call close first. // This way we can push tcp Time_Wait to server side when possible. await Task.Delay(1000); proxyServer.UpdateServerConnectionCount(false); Stream.Dispose(); try { TcpSocket.Close(); } catch { // ignore } }); disposed = true; }
private async void TryConnectToController() { if (controllerClient != null) { textToaster.Toast("A controller is already connected."); return; } if (!ConnectWindowVisibility) { textToaster.Toast("Cannot try connecting to more than one remote machine."); return; } ConnectWindowVisibility = false; var random = new System.Random(); int userId = random.Next(); var tcpSocket = new TcpSocket(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)); if (await tcpSocket.ConnectAsync(IPAddress.Loopback, ControllerMessages.PORT)) { textToaster.Toast("connected"); controllerClient = new ControllerClient(userId, tcpSocket); } else { textToaster.Toast("not connected"); } ConnectWindowVisibility = true; }
private void OnData(TcpSocket socket, ArraySegment <byte> data) { int received = _parser.Execute(data.Array, data.Offset, data.Count); if (_parser.Errno == HttpParserError.PAUSED) { if (data.Count > received) { _pausedData = new ArraySegment <byte>(data.Array, data.Offset + received, data.Count - received); } if (_parser.Upgrade) { _socket.OnConnected -= OnSocketConnected; _socket.OnDisconnected -= OnSocketDisconnected; _socket.OnData -= OnData; _server.HandleUpgrade(_msg, _socket, _pausedData); } else { _server.HandleRequest(_msg, this); } } else if (_parser.Errno != HttpParserError.OK) { Close(); } }
public void ReadShouldCancelWhileAwaitingResponse() { var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) using (var test = new TcpSocket(endpoint, log: TestConfig.InfoLog)) { var count = 0; var semaphore = new SemaphoreSlim(0); var token = new CancellationTokenSource(); test.ReadAsync(4, token.Token).ContinueWith(t => { Interlocked.Increment(ref count); Assert.That(t.IsCanceled, Is.True, "Task should be set to cancelled when disposed."); semaphore.Release(); }); Thread.Sleep(100); token.Cancel(); semaphore.Wait(TimeSpan.FromSeconds(1)); Assert.That(count, Is.EqualTo(1), "Read should have cancelled and incremented count."); } }
static void Main(string[] args) { int port = 5555; Console.WriteLine(string.Format("Client Başlatıldı. Port: {0}", port)); Console.WriteLine("-----------------------------"); TcpSocket tcpSocket = new TcpSocket(new IPEndPoint(IPAddress.Parse("127.0.0.1"), port)); tcpSocket.Start(); Console.WriteLine("Göndermek için \"S\", basınız..."); int count = 1; while (Console.ReadLine().ToUpper() == "S") { DataTransferObject dataTransferObject = new DataTransferObject() { Status = string.Format("{0}. Alındı", count), Message = string.Format("{0} ip numaralı client üzerinden geliyorum!", GetLocalIPAddress()) }; tcpSocket.SendData(dataTransferObject); count++; } Console.ReadLine(); }
public void ReadShouldNotLoseDataFromStreamOverMultipleReads() { var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) using (var test = new TcpSocket(endpoint, log: TestConfig.InfoLog)) { const int firstMessage = 99; const string secondMessage = "testmessage"; var bytes = Encoding.UTF8.GetBytes(secondMessage); var payload = new KafkaWriter() .Write(firstMessage) .Write(bytes, false); //send the combined payload var send = server.SendDataAsync(payload.ToBytesNoLength()); var firstResponse = test.ReadAsync(4, CancellationToken.None).Result.ToInt32(); Assert.That(firstResponse, Is.EqualTo(firstMessage)); var secondResponse = Encoding.ASCII.GetString(test.ReadAsync(secondMessage.Length, CancellationToken.None).Result); Assert.That(secondResponse, Is.EqualTo(secondMessage)); } }
public void StartReceive(IPAddress Address, int Port, string FilePath) { // store destination path _filePath = FilePath; // initialize the file socket _clientSocket = new TcpSocket(); // use the FileDataReceived callback _clientSocket.DataReceived += new TcpSocket.DataReceivedDelegate(OnDataReceived); _clientSocket.Connected += new TcpSocket.ConnectedDelegate(OnConnected); _clientSocket.DisConnected += new TcpSocket.DisConnectedDelegate(OnDisConnected); _clientSocket.Connect(Address, Port); if (!_clientSocket.IsConnected) { // connect attempt failed throw new CryptoSocketException("DtmFileTransfer:StartReceive", "Could not connect to the remote host!", new SocketException((int)SocketError.ConnectionAborted)); } else { // create the temp file note: is WriteThrough more secure here? _tempPath = Path.Combine(Path.GetDirectoryName(_filePath), Path.GetFileNameWithoutExtension(Path.GetRandomFileName()) + ".tmp"); using (new FileStream(_tempPath, FileMode.Create, FileAccess.Write, FileShare.Read)) { } // set to hidden to avoid cross process errors File.SetAttributes(_tempPath, File.GetAttributes(_tempPath) | FileAttributes.Hidden); _clientSocket.ReceiveBufferSize = m_bufferSize; _clientSocket.SendBufferSize = m_bufferSize; // start receiving _clientSocket.ReceiveAsync(); _clientSocket.ReceiveTimeout = -1; // connection established _isConnected = true; } }
public async Task WriteShouldCancelWhileSendingData() { var writeAttempts = 0; var config = new ConnectionConfiguration(onWriting: (e, payload) => Interlocked.Increment(ref writeAttempts)); var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) using (var test = new TcpSocket(endpoint, config, TestConfig.InfoLog)) using (var token = new CancellationTokenSource()) { var write = test.WriteAsync(new DataPayload(1.ToBytes()), token.Token); await TaskTest.WaitFor(() => server.ConnectionEventcount > 0); await TaskTest.WaitFor(() => writeAttempts > 0); Assert.That(writeAttempts, Is.EqualTo(1), "Socket should have attempted to write."); //create a buffer write that will take a long time var data = Enumerable.Range(0, 100000000).Select(b => (byte)b).ToArray(); token.Cancel(); var taskResult = test.WriteAsync( new DataPayload(data), token.Token); await Task.WhenAny(taskResult, Task.Delay(TimeSpan.FromSeconds(5))).ConfigureAwait(false); Assert.That(taskResult.IsCanceled, Is.True, "Task should have cancelled."); } }
public void ReadShouldStackReadRequestsAndReturnOneAtATime() { var endpoint = Endpoint.Resolve(TestConfig.ServerUri(), TestConfig.InfoLog); using (var server = new FakeTcpServer(TestConfig.InfoLog, endpoint.IP.Port)) { var messages = new[] { "test1", "test2", "test3", "test4" }; var expectedLength = "test1".Length; var payload = new KafkaWriter().Write(messages); using (var socket = new TcpSocket(endpoint, log: TestConfig.WarnLog)) { var tasks = messages.Select(x => socket.ReadAsync(x.Length, CancellationToken.None)).ToArray(); var send = server.SendDataAsync(payload.ToBytes()); Task.WaitAll(tasks); foreach (var task in tasks) { Assert.That(task.Result.Length, Is.EqualTo(expectedLength)); } } } }
public async Task <LoopSession> Start() { int?port; ReceiverService loop = new ReceiverBuilder() .WithDefinition(new LoopMessages()) .Build(hooks); TcpSocket client = pool.New(); TcpSocket server = pool.New(); client.Bind(); server.Bind(out port); server.Listen(1); IPEndPoint endpoint = new IPEndPoint(IPAddress.Loopback, port.Value); Task <TcpSocketAccept> accept = server.Accept(); client.Connect(endpoint, null); PeerHash peer = PeerHash.Random(); TcpSocketAccept accepted = await accept; NetworkConnection receiver = pool.Create(accepted.Connection, NetworkDirection.Incoming, accepted.GetRemote()); loop.StartProcessing(peer, receiver); return(new LoopSession(client, loop)); }
public void PauseShouldPreventNewConnections() { ServerHelper.EchoServer((server, port, sync) => { server.Pause(5000); // prevent connections for 5 seconds Assert.IsTrue(server.IsPaused, "Server should be paused"); var socket = new TcpSocket(TcpSocketType.IPv4); socket.Data += (data, count) => Assert.Fail("We should never receive data"); socket.Connect(port, connectedCallback: self => { Assert.IsTrue(server.IsPaused, "Server should be paused"); self.Write("test"); Thread.Sleep(2000); Assert.IsFalse(self.IsConnected); sync.SignalAndWait(); }); Thread.Sleep(10000); Assert.IsFalse(server.IsPaused, "Server should be unpaused"); //accepting connections socket = new TcpSocket(TcpSocketType.IPv4); socket.Connect(port, connectedCallback: self => { Assert.IsTrue(self.IsConnected); sync.SignalAndWait(); }); }, 3); }
async protected override Task InitializeConnectionAsync(TcpSocket Client) { var Stream = new SslStream( innerStream: Client.Stream, leaveInnerStreamOpen: false, userCertificateValidationCallback: (Sender, Certificate, Chain, SslPolicyErrors) => { //Console.WriteLine("userCertificateValidationCallback"); return true; }, userCertificateSelectionCallback: (Sender, TargetHost, LocalCertificates, RemoteCertificate, AcceptableIssuers) => { //Console.WriteLine("Host: '{0}'", targetHost); //Console.WriteLine(String.Join(",", acceptableIssuers)); if (HostCertificates.ContainsKey(TargetHost)) { return HostCertificates[TargetHost]; } else { return DefaultX509Certificate; } } ); await Stream.AuthenticateAsServerAsync(DefaultX509Certificate); //await Stream.AuthenticateAsServerAsync(X509Certificate, true, SslProtocols.Tls, true); Client.UnsafeSetStream(Stream); }
private async Task AcceptClientAsync() { SocketAwaitable awaitable = Pools.SocketAwaitable.Take(); try { while (!_cts.IsCancellationRequested) { var error = await _listenerSocket.AcceptAsync(awaitable); if (error == SocketError.ConnectionReset) { continue; } if (error == SocketError.OperationAborted) { _log.Error($"{error} returned by AcceptClientAsync - requesting cancellation and shutting down."); _cts.Cancel(); break; } if (error != SocketError.Success) { _log.Error($"AcceptAsync failed with error: {error}"); continue; } var socket = new TcpSocket(awaitable.EventArgs.AcceptSocket); socket.NoDelay = true; // Null it now so we don't dispose of it in the finally clause. awaitable.EventArgs.AcceptSocket = null; var client = _clientFactory(); var ep = socket.RemoteEndPoint; client.SetSocket(socket); _lock.EnterWriteLock(); try { _clients.Add(client); } finally { _lock.ExitWriteLock(); } _log.Debug($"Client from {ep} successfully connected."); } } finally { awaitable.EventArgs.AcceptSocket?.Dispose(); awaitable.EventArgs.AcceptSocket = null; Pools.SocketAwaitable.Return(awaitable); } }
public void CeckForEquality() { var socketOne = new TcpSocket(); var socketTwo = new TcpSocket(); Assert.AreNotEqual(socketTwo, socketOne); Assert.AreEqual(socketOne, socketOne); Assert.AreEqual(new TcpSocket((Socket)socketOne), socketOne); }
public void Connect(Connection connection, Address address, bool noVerification) { var ipHostEntry = Dns.GetHostEntry(address.Host); Exception exception = null; TcpSocket socket = null; foreach (var ipAddress in ipHostEntry.AddressList) { if (ipAddress == null) { continue; } try { socket = new TcpSocket(); socket.Connect(new IPEndPoint(ipAddress, address.Port)); exception = null; break; } catch (SocketException socketException) { if (socket != null) { socket.Close(); socket = null; } exception = socketException; } } if (exception != null) { throw exception; } if (address.UseSsl) { SslSocket sslSocket = new SslSocket(socket); sslSocket.AuthenticateAsClient( address.Host, null, noVerification ? SslVerification.NoVerification : SslVerification.VerifyPeer, SslProtocols.Default); this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
////////////////////////////////////////////////////////////////////////// // Communication ////////////////////////////////////////////////////////////////////////// public TcpSocket bind(TcpSocket fan, IpAddr addr, Long port) { try { IPAddress dotnetAddr = (addr == null) ? IPAddress.Any : addr.m_peer.m_dotnet; int dotnetPort = (port == null) ? 0 : port.intValue(); m_dotnet.Bind(new IPEndPoint(dotnetAddr, dotnetPort)); return fan; } catch (SocketException e) { throw IOErr.make(e).val; } }
public void Connect(Connection connection, Address address, bool noVerification) { TcpSocket socket = new TcpSocket(); socket.Connect(address.Host, address.Port); if (address.UseSsl) { SslSocket sslSocket = new SslSocket(socket, noVerification); sslSocket.AuthenticateAsClient(address.Host); this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
public void ServerRemovesStaleConnections() { ServerHelper.Server((server, port, sync) => { var socket = new TcpSocket(TcpSocketType.IPv4); socket.Connect(port, connectedCallback: self => { Thread.Sleep(500); Assert.AreEqual(1, server.ConnectionCount, "we are connected"); self.Dispose(); Thread.Sleep(500); Assert.AreEqual(0, server.ConnectionCount, "no connections now"); sync.SignalAndWait(); }); }, timeout: 30); }
async private Task ConnectAsync(string User, string Password) { Socket = await TcpSocket.CreateAndConnectAsync("talk.google.com", 5222); bool Authenticated = false; while (true) { Console.WriteLine("--------------------------"); await Socket.WriteAsync("<stream:stream to='gmail.com' xmlns:stream='http://etherx.jabber.org/streams' xmlns='jabber:client' version='1.0'>"); //await Socket.ReadBytesAsync(138); Reader = XmlReader.Create(Socket.Stream, new XmlReaderSettings() { Async = true, ConformanceLevel = ConformanceLevel.Fragment }); await Reader.ReadAsync(); await Reader.ReadAsync(); Reader = Reader.ReadSubtree(); await Reader.ReadAsync(); var FeaturesXml = await WaitEndElementAsync("stream:features"); var starttls = FeaturesXml.OuterXml.Contains("starttls"); //Console.WriteLine("starttls: {0}", starttls); //Console.ReadKey(); if (starttls) { await Socket.WriteAsync("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'><required /></starttls>"); await WaitEndElementAsync("proceed"); await Socket.SecureSslAsync("gmail.com"); Console.WriteLine("StartTLS"); } else if (!Authenticated) { await Socket.WriteAsync(String.Format("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>{0}</auth>", Convert.ToBase64String(Encoding.Default.GetBytes(String.Format("\0{0}\0{1}", User, Password))))); await WaitEndElementAsync("success"); Authenticated = true; } else { await Socket.WriteAsync(String.Format("<iq xmlns='jabber:client' type='set' id='1'><bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'><resource>{0}</resource></bind></iq>", "NodeNet")); var IqNode = await WaitEndElementAsync("iq"); Console.WriteLine(IqNode.OuterXml); Console.ReadKey(); return; } } }
public void setOutBufferSize(TcpSocket fan, Long v) { if (m_in != null) throw Err.make("Must set outBufSize before connection").val; m_outBufSize = (v == null) ? 0 : v.intValue(); }
public async Task ConnectAsync(Address address, ConnectionFactory factory) { IPAddress[] ipAddresses; IPAddress ip; if (IPAddress.TryParse(address.Host, out ip)) { ipAddresses = new IPAddress[] { ip }; } else { ipAddresses = await TaskExtensions.GetHostAddressesAsync(address.Host); } // need to handle both IPv4 and IPv6 Socket socket = null; Exception exception = null; for (int i = 0; i < ipAddresses.Length; i++) { if (ipAddresses[i] == null || (ipAddresses[i].AddressFamily == AddressFamily.InterNetwork && !Socket.OSSupportsIPv4) || (ipAddresses[i].AddressFamily == AddressFamily.InterNetworkV6 && !Socket.OSSupportsIPv6)) { continue; } socket = new Socket(ipAddresses[i].AddressFamily, SocketType.Stream, ProtocolType.Tcp); try { await socket.ConnectAsync(ipAddresses[i], address.Port); exception = null; break; } catch (Exception e) { exception = e; socket.Dispose(); socket = null; } } if (socket == null) { throw exception ?? new SocketException((int)SocketError.AddressNotAvailable); } if (factory.tcpSettings != null) { factory.tcpSettings.Configure(socket); } IAsyncTransport transport; if (address.UseSsl) { SslStream sslStream; var ssl = factory.SslInternal; if (ssl == null) { sslStream = new SslStream(new NetworkStream(socket)); await sslStream.AuthenticateAsClientAsync(address.Host); } else { sslStream = new SslStream(new NetworkStream(socket), false, ssl.RemoteCertificateValidationCallback, ssl.LocalCertificateSelectionCallback); await sslStream.AuthenticateAsClientAsync(address.Host, ssl.ClientCertificates, ssl.Protocols, ssl.CheckCertificateRevocation); } transport = new SslSocket(this, sslStream); } else { transport = new TcpSocket(this, socket); } this.socketTransport = transport; this.writer = new Writer(this, this.socketTransport); }
public async Task ConnectAsync(Address address, ConnectionFactory factory) { Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp); if (factory.tcpSettings != null) { factory.tcpSettings.Configure(socket); } await Task.Factory.FromAsync( (c, s) => ((Socket)s).BeginConnect(address.Host, address.Port, c, s), (r) => ((Socket)r.AsyncState).EndConnect(r), socket); IAsyncTransport transport; if (address.UseSsl) { SslStream sslStream; var ssl = factory.SslInternal; if (ssl == null) { sslStream = new SslStream(new NetworkStream(socket)); await sslStream.AuthenticateAsClientAsync(address.Host); } else { sslStream = new SslStream(new NetworkStream(socket), false, ssl.RemoteCertificateValidationCallback, ssl.LocalCertificateSelectionCallback); await sslStream.AuthenticateAsClientAsync(address.Host, ssl.ClientCertificates, ssl.Protocols, ssl.CheckCertificateRevocation); } transport = new SslSocket(this, sslStream); } else { transport = new TcpSocket(this, socket); } this.socketTransport = transport; this.writer = new Writer(this, this.socketTransport); }
public void setTrafficClass(TcpSocket fan, long v) { m_dotnet.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.TypeOfService, (int)v); }
static void Main(string[] args) { Console.WriteLine("----------------------------------"); Console.WriteLine("----------------------------------"); Console.WriteLine("------ Pokemon World Server ------"); Console.WriteLine("----------------------------------"); Console.WriteLine("----------------------------------"); Console.WriteLine(""); World.Instance.Init(GetMap()); World.Instance.LoadPopulation(); using (var socket = new TcpSocket()) { #region start module loop var updateLoop = new Thread(new ThreadStart(UpadateModules)); updateLoop.Name = "UpdateLoop"; updateLoop.Start(); #endregion #region set network on socket.StartListening(ConnectionRequested, MessageReceived, Disconnected); Console.WriteLine(); Console.WriteLine("Server listening on port " + socket.Port); Console.WriteLine(); #endregion Console.WriteLine("Press any key to stop the server..."); Console.WriteLine(); var key = Console.ReadKey(); Console.WriteLine(); #region stop module loop STOP = true; while (updateLoop.IsAlive) { Thread.Sleep(10); } #endregion #region set network off socket.StopListening(); #endregion } Console.WriteLine("----------------------------------"); Console.WriteLine("----------------------------------"); Console.WriteLine("------ Pokemon World Server ------"); Console.WriteLine("----------------------------------"); Console.WriteLine("----------------------------------"); Console.WriteLine(); Console.WriteLine("Server stopped. Press any key to exit..."); Console.WriteLine(); Console.ReadKey(); }
public void setLinger(TcpSocket fan, Duration v) { if (v == null) { m_dotnet.LingerState = new LingerOption(false, 0); } else { m_dotnet.LingerState = new LingerOption(true, (int)(v.sec())); } }
public OutStream @out(TcpSocket fan) { if (m_out == null) throw IOErr.make("not connected").val; return m_out; }
public InStream @in(TcpSocket fan) { if (m_in == null) throw IOErr.make("not connected").val; return m_in; }
public void Connect(Connection connection, Address address, bool noVerification) { var ipHostEntry = Dns.GetHostEntry(address.Host); Exception exception = null; TcpSocket socket = null; // reference to SSL socket, wrapper for above TCP socket SslSocket sslSocket = null; foreach (var ipAddress in ipHostEntry.AddressList) { if (ipAddress == null) { continue; } try { socket = new TcpSocket(); // SSL connection requested with an SSL host if (address.UseSsl) { // wrap TCP socket to SSL socket sslSocket = new SslSocket(socket, address.Host, ValidateCertificate); } socket.Connect(new IPEndPoint(ipAddress, address.Port)); exception = null; break; } catch (SocketException socketException) { if (address.UseSsl) { if (sslSocket != null) { sslSocket.Close(); sslSocket = null; } } if (socket != null) { socket.Close(); socket = null; } exception = socketException; } } if (exception != null) { throw exception; } if (address.UseSsl) { this.socketTransport = sslSocket; } else { this.socketTransport = socket; } }
public async Task ConnectAsync(Address address, ConnectionFactory factory) { Socket socket; IPAddress[] ipAddresses; IPAddress ipAddress; if (IPAddress.TryParse(address.Host, out ipAddress)) { socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); ipAddresses = new IPAddress[] { ipAddress }; } else { socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ipAddresses = Dns.GetHostEntry(address.Host).AddressList; } if (factory.tcpSettings != null) { factory.tcpSettings.Configure(socket); } await Task.Factory.FromAsync( (c, s) => ((Socket)s).BeginConnect(ipAddresses, address.Port, c, s), (r) => ((Socket)r.AsyncState).EndConnect(r), socket); IAsyncTransport transport; if (address.UseSsl) { SslStream sslStream; var ssl = factory.SslInternal; if (ssl == null) { sslStream = new SslStream(new NetworkStream(socket)); await sslStream.AuthenticateAsClientAsync(address.Host); } else { sslStream = new SslStream(new NetworkStream(socket), false, ssl.RemoteCertificateValidationCallback); await sslStream.AuthenticateAsClientAsync(address.Host, ssl.ClientCertificates, ssl.Protocols, ssl.CheckCertificateRevocation); } transport = new SslSocket(this, sslStream); } else { transport = new TcpSocket(this, socket); } this.socketTransport = transport; this.writer = new Writer(this, this.socketTransport); }
public void setReceiveBufferSize(TcpSocket fan, long v) { m_dotnet.ReceiveBufferSize = (int)v; }
public void setReceiveTimeout(TcpSocket fan, Duration v) { if (v == null) m_dotnet.ReceiveTimeout = 0; else m_dotnet.ReceiveTimeout = (int)(v.millis()); }
public void setReuseAddr(TcpSocket fan, bool v) { m_dotnet.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, v); }
public void setSendBufferSize(TcpSocket fan, long v) { m_dotnet.SendBufferSize = (int)v; }
protected override async Task ReadHeadersAsync(TcpSocket Client, HttpRequest Request, HttpResponse Response) { Request.Schema = "https"; await base.ReadHeadersAsync(Client, Request, Response); }
public bool close(TcpSocket fan) { try { close(); return true; } catch { return false; } }
public void setNoDelay(TcpSocket fan, bool v) { m_dotnet.NoDelay = v; }
static bool TryCreateTcpSocket(string ip, int port, out Socket socket) { socket = null; IPAddress address; if (!IPAddress.TryParse (ip, out address)) return false; socket = new TcpSocket (address, port); return true; }
void Awake() { instance = this; tcpSocket = new TcpSocket(); }
static bool TryCreateTcpSocket(ConfigurationManager configurationManager, string[] socketParts, out Socket socket) { socket = null; ushort port; try { if (socketParts.Length > 1) { if (!UInt16.TryParse (socketParts [socketParts.Length - 1], out port)) { Logger.Write (LogLevel.Error, "Error parsing port number"); return false; } } else { port = configurationManager.Port; } } catch (ApplicationException e) { Logger.Write (LogLevel.Error, e.Message); return false; } IPAddress address = configurationManager.Address; if (socketParts.Length == 3) { string address_str = socketParts [1]; if (address_str == null) address = IPAddress.Loopback; else if (!IPAddress.TryParse (address_str, out address)) { Logger.Write (LogLevel.Error, "Error in argument \"address\". \"{0}\" cannot be converted to an IP address.", address_str); return false; } } try { socket = new TcpSocket (address, port); } catch (System.Net.Sockets.SocketException e) { Logger.Write (LogLevel.Error, "Error creating the socket: {0}", e.Message); return false; } Logger.Write (LogLevel.Debug, "Listening on port: {0}", port); Logger.Write (LogLevel.Debug, "Listening on address: {0}", address); return true; }
internal void connected(TcpSocket fan) { IPEndPoint endPoint = m_dotnet.RemoteEndPoint as IPEndPoint; m_remoteAddr = IpAddrPeer.make(endPoint.Address); m_remotePort = endPoint.Port; m_in = SysInStream.make(new NetworkStream(m_dotnet), getInBufferSize(fan)); m_out = SysOutStream.make(new NetworkStream(m_dotnet), getOutBufferSize(fan)); }
////////////////////////////////////////////////////////////////////////// // Peer Factory ////////////////////////////////////////////////////////////////////////// public static TcpSocketPeer make(TcpSocket fan) { return new TcpSocketPeer(); }