public TCPSocket(Socket from, bool socket_listening) { sock = from; listening = socket_listening; if (socket_listening) { IPEndPoint tmp = (IPEndPoint)sock.LocalEndPoint; port = (ushort)tmp.Port; ep = tmp; } else { IPEndPoint tmp = (IPEndPoint)sock.RemoteEndPoint; port = (ushort)tmp.Port; ep = tmp; } if (sock.Blocking == false) { sock.Blocking = true; } sock.ReceiveBufferSize = 1024 * 64; // 64 kb sock.SendBufferSize = 1024 * 64; // 64 kb }
public override int DoRead(byte[] buffer) { System.Net.EndPoint endpoint = (System.Net.EndPoint)sendTarget; int size = client.ReceiveFrom(buffer, ref endpoint); return(size); }
public void Connect(EndPoint endPoint) { byte[] data = new byte[1024]; string input, stringData; int recv; Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); int sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); Console.WriteLine("Default timeout: {0}", sockopt); server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, _timeout); sockopt = (int)server.GetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout); Console.WriteLine("New timeout: {0}", sockopt); string welcome = "Hello, are you there?"; data = Encoding.ASCII.GetBytes(welcome); server.SendTo(data, data.Length, SocketFlags.None, endPoint); data = new byte[1024]; try { Console.WriteLine("Waiting from {0}:", endPoint.ToString()); recv = server.ReceiveFrom(data, ref endPoint); Console.WriteLine("Message received from {0}:", endPoint.ToString()); Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv)); } catch (SocketException e) { if (e.SocketErrorCode == SocketError.HostUnreachable) throw new Exception("CLOSED"); throw new Exception("TIME_OUT"); } Console.WriteLine("Stopping client"); server.Close(); }
internal EndpointI(Instance instance, string ho, int po, EndPoint sourceAddr, int ti, string conId, bool co) : base(instance, ho, po, sourceAddr, conId) { _instance = instance; _timeout = ti; _compress = co; }
public UDPPacketBuffer() { this.Data = new byte[BUFFER_SIZE]; // this will be filled in by the call to udpSocket.BeginReceiveFrom RemoteEndPoint = (EndPoint)new IPEndPoint(IPAddress.Any, 0); }
Task<ActiveConnectResult> IActiveConnector.ActiveConnect(EndPoint targetEndPoint) { var taskSource = new TaskCompletionSource<ActiveConnectResult>(); var socket = new Socket(targetEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); socket.BeginConnect(targetEndPoint, OnActiveConnectCallback, new ActiveConnectState(taskSource, socket)); return taskSource.Task; }
protected UnixSocket (EndPoint localEndPoint) : base (System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.IP, localEndPoint) { }
/// <summary> /// <see cref="AbstractTcpClient.ConnectInternal"/> /// </summary> protected override void ConnectInternal(Socket socket, EndPoint endpoint) { try { if (Object.ReferenceEquals(socket, null)) { socket = new Socket( endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp); } if (Object.ReferenceEquals(connectEventArgs, null)) { connectEventArgs = new SocketAsyncEventArgs(); connectEventArgs.Completed += OnConnectCompleted; } connectEventArgs.RemoteEndPoint = endpoint; connectEventArgs.UserToken = socket; bool pending = socket.ConnectAsync(connectEventArgs); if (!pending) { OnConnect(connectEventArgs); } } catch (Exception e) { Log.Error("{0} error connecting to {1} : {2}", Name, endpoint, e.Message); OnConnectError(socket, endpoint); } }
internal NetState(EndPoint ep) { EndPoint = ep; AddClient(this); LogLine("Connected"); }
public void BeginReceiveAll(byte[] buffer, int count, EndPoint remoteEndPoint) { ValidateTransferAllArguments(buffer, ref count); var transfered = 0; AsyncCallback callback = null; callback = result => { var endPoint = result.AsyncState as EndPoint; if (endPoint == null) return; var current = Socket.EndReceiveFrom(result, ref endPoint); if (current == 0) { ReceiveCompleted?.Invoke(this, new TransferEventArgs(this, buffer, transfered, endPoint)); return; } transfered += current; if (transfered < current) Socket.BeginReceiveFrom(buffer, transfered, count - transfered, SocketFlags.None, ref endPoint, callback, endPoint); else ReceiveCompleted?.Invoke(this, new TransferEventArgs(this, buffer, transfered, endPoint)); }; Socket.BeginReceiveFrom(buffer, transfered, count - transfered, SocketFlags.None, ref remoteEndPoint, callback, remoteEndPoint); }
public NetworkDevice(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, EndPoint endPoint) { _AddressFamily = addressFamily; _SocketType = socketType; _ProtocolType = protocolType; _EndPoint = endPoint; }
/// <summary> /// Constructor /// </summary> /// <param name="endPoint">Specifies endpoint of sender</param> /// <param name="msg">Message associated with event</param> /// <param name="_packet">Packet received</param> /// <param name="exception">Any exception, if occured</param> public NetEventArgs(EndPoint endPoint, string msg, NetPacket _packet, Exception exception) { this._endPoint = endPoint; this._msg = msg; this._packet = _packet; this._exception = exception; }
private void Connect_Click(object sender, EventArgs e) { try { epLocal = new IPEndPoint(IPAddress.Parse(IPClient_1.Text), Convert.ToInt32(PortClient_1.Text)); sck.Bind(epLocal); epRemote = new IPEndPoint(IPAddress.Parse(IPClient_2.Text), Convert.ToInt32(PortClient_2.Text)); sck.Connect(epRemote); byte[] buffer = new byte[1500]; sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer); Connect.Enabled = false; Send.Enabled = true; Сondition.Text = "Подключено"; tbSend.Focus(); form1.Form1_IPClient_1 = IPClient_1.Text; form1.Form1_IPClient_2 = IPClient_2.Text; form1.Form1_PortClient_1 = PortClient_1.Text; form1.Form1_PortClient_2 = PortClient_2.Text; form1.Player1.Text = NameClient_1.Text; form1.Player2.Text = NameClient_2.Text; } catch (Exception ex) { //MessageBox.Show(ex.ToString()); MessageBox.Show("Проблема с подключением, проверте: \r\n - верно ли внесены сетевые настройки игры;\r\n - отсутствует сетевое подключение;\r\n - Ваш противник покинул игру или неуспел подключится.", "Oшибка!!!", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification); } }
public Connect(EndPoint remoteEndPoint) { if (remoteEndPoint == null) throw new ArgumentNullException("remoteEndPoint"); _remoteEndPoint = remoteEndPoint; }
public EchoConnectionHandler(EndPoint remote, IActorRef connection) { // we want to know when the connection dies (without using Tcp.ConnectionClosed) Context.Watch(connection); Receive<Tcp.Received>(received => { var text = Encoding.UTF8.GetString(received.Data.ToArray()).Trim(); Console.WriteLine("Received '{0}' from remote address [{1}]", text, remote); if (text == "exit") Context.Stop(Self); else Sender.Tell(Tcp.Write.Create(received.Data)); }); Receive<Tcp.ConnectionClosed>(closed => { Console.WriteLine("Stopped, remote connection [{0}] closed", remote); Context.Stop(Self); }); Receive<Terminated>(terminated => { Console.WriteLine("Stopped, remote connection [{0}] died", remote); Context.Stop(Self); }); }
public void BeginConnectProxy(EndPoint remoteEP, AsyncCallback callback, object state) { // do nothing var r = new FakeAsyncResult(state); callback?.Invoke(r); }
public XSPWorker(Socket client, EndPoint localEP, ApplicationServer server, bool secureConnection, Mono.Security.Protocol.Tls.SecurityProtocolType SecurityProtocol, X509Certificate cert, PrivateKeySelectionCallback keyCB, bool allowClientCert, bool requireClientCert) { if (secureConnection) { ssl = new SslInformation (); ssl.AllowClientCertificate = allowClientCert; ssl.RequireClientCertificate = requireClientCert; ssl.RawServerCertificate = cert.GetRawCertData (); netStream = new LingeringNetworkStream (client, true); SslServerStream s = new SslServerStream (netStream, cert, requireClientCert, false); s.PrivateKeyCertSelectionDelegate += keyCB; s.ClientCertValidationDelegate += new CertificateValidationCallback (ClientCertificateValidation); stream = s; } else { netStream = new LingeringNetworkStream (client, false); stream = netStream; } sock = client; this.server = server; this.remoteEP = (IPEndPoint) client.RemoteEndPoint; this.localEP = (IPEndPoint) localEP; }
public bool HandleFlood(EndPoint id) { if (_floods.ContainsKey(id)) { FloodCount counter = _floods[id]; counter.PacketCount++; _floods[id] = counter; if (counter.StopWatch.ElapsedMilliseconds > _msecTime) { _floods.Remove(id); } else { _floods.Remove(id); return false; } } else { FloodCount counter = new FloodCount(); counter.PacketCount = 1; counter.StopWatch.Start(); _floods.Add(id, counter); } return true; }
State GetState(EndPoint ep, TimeSpan rtt) { if (_states == null) { lock (this) { if (_state == null && !InvalidValue.Equals (rtt)) _state = new State ((int)rtt.TotalMilliseconds, _timerGranularity); return _state; } } IPEndPoint ipep = ep as IPEndPoint; if (ipep == null) throw new ArgumentException (); State state; bool success; using (_lock.EnterReadLock ()) { success = _states.TryGetValue (ipep.Address, out state); } if (!success && !InvalidValue.Equals (rtt)) { using (_lock.EnterWriteLock ()) { if (!_states.TryGetValue (ipep.Address, out state)) { state = new State ((int)rtt.TotalMilliseconds, _timerGranularity); _states.Add (ipep.Address, state); } } } return state; }
public TimeSpan GetRTO(EndPoint ep) { State state = GetState (ep, InvalidValue); if (state == null) return _defaultRTO; return new TimeSpan (Math.Max (_minRTO, state.RTO) * TimeSpan.TicksPerMillisecond); }
/// <summary> /// This code is used to connect to a TCP socket with timeout option. /// </summary> /// <param name="endPoint">IP endpoint of remote server</param> /// <param name="timeoutMs">Timeout to wait until connect</param> /// <returns>Socket object connected to server</returns> public static Socket ConnectToServerWithTimeout(EndPoint endPoint, int timeoutMs) { var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { socket.Blocking = false; socket.Connect(endPoint); socket.Blocking = true; return socket; } catch (SocketException socketException) { if (socketException.ErrorCode != 10035) { socket.Close(); throw; } if (!socket.Poll(timeoutMs * 1000, SelectMode.SelectWrite)) { socket.Close(); throw new NGRIDException("The host failed to connect. Timeout occured."); } socket.Blocking = true; return socket; } }
// static methods internal static MongoWaitQueueFullException ForConnectionPool(EndPoint endPoint) { var message = string.Format( "The wait queue for acquiring a connection to server {0} is full.", EndPointHelper.ToString(endPoint)); return new MongoWaitQueueFullException(message); }
internal ServerCounters(EndPoint endpoint) { this.EndPoint = endpoint; this.Interactive = new ConnectionCounters(ConnectionType.Interactive); this.Subscription = new ConnectionCounters(ConnectionType.Subscription); this.Other = new ConnectionCounters(ConnectionType.None); }
public PolicyConnection(PolicyServer policyServer, Socket client, byte[] policy) { _policyServer = policyServer; _connection = client; _endpoint = _connection.RemoteEndPoint; _policy = policy; _buffer = new byte[_policyRequestString.Length]; _received = 0; try { // Receive the request from the client _connection.BeginReceive(_buffer, 0, _policyRequestString.Length, SocketFlags.None, new AsyncCallback(OnReceive), null); } catch (SocketException ex) { if (log.IsDebugEnabled) log.Debug("Socket exception", ex); _connection.Close(); } catch (Exception ex) { if (log.IsErrorEnabled) log.Error("Failed starting a policy connection", ex); } }
protected override void CreateMessagingSocket(int idx, SymmetricKey key, out IMessagingSocket socket, out EndPoint endPoint) { endPoint = new IPEndPoint (_adrsGen.Next (), 10000); VirtualDatagramEventSocket sock = new VirtualDatagramEventSocket (_net, ((IPEndPoint)endPoint).Address); sock.Bind (endPoint); socket = new VirtualMessagingSocket (sock, true, _interrupter, DefaultRTO, DefaultRetryCount, 1024, 1024); }
private UdpChannel AddClient(System.Net.Sockets.Socket socket, System.Net.EndPoint remotpoint, string key) { UdpChannel channel = new UdpChannel(mSocket, this, remotpoint); OnConnected(channel); if (mConnectEA.Cancel) { channel.Dispose(); return(null); } else { channel.ChannelDisposed = OnChannelDispose; channel.ChannelError = OnChannelError; channel.ChannelReceive = OnChannelReceive; channel.ChannelSend = OnChannelSend; lock (mClients) { mClients.Add(key, channel); Version++; } } return(channel); }
/// <summary> /// Constructor. /// </summary> /// <param name="hostEndPoint">Identifies a Network resource that this server is listening on.</param> /// <param name="bufferSize">Size of the buffer to use when receiving data from a connected client.</param> /// <param name="clientReadTimeout">amount of time that the server will wait /// for a client to send data before timing the client out.</param> /// <param name="clientSendTimeout">amount of time that the server will wait /// for a client to receive data before timing the client out.</param> public SocketServer(EndPoint hostEndPoint, int bufferSize, TimeSpan clientReadTimeout, TimeSpan clientSendTimeout) { _hostEndPoint = hostEndPoint; _bufferSize = bufferSize; _clientReadTimeout = clientReadTimeout; _clientSendTimeout = clientSendTimeout; }
public void Bind2(EndPoint ep) { if (ep == null) Bind(new IPEndPoint(IPAddress.Any, 0)); else Bind(ep); }
public void beginWrite(EndPoint endpoint, Buffer buf) { if(!(endpoint is IPEndPoint)) { throw new Ice.FeatureNotSupportedException("SOCKS4 does not support domain names"); } else if(endpoint.AddressFamily != AddressFamily.InterNetwork) { throw new Ice.FeatureNotSupportedException("SOCKS4 only supports IPv4 addresses"); } // // SOCKS connect request // IPEndPoint addr = (IPEndPoint)endpoint; buf.resize(9, false); ByteBuffer.ByteOrder order = buf.b.order(); buf.b.order(ByteBuffer.ByteOrder.BIG_ENDIAN); // Network byte order. buf.b.position(0); buf.b.put(0x04); // SOCKS version 4. buf.b.put(0x01); // Command, establish a TCP/IP stream connection buf.b.putShort((short)addr.Port); // Port buf.b.put(addr.Address.GetAddressBytes()); // IPv4 address buf.b.put(0x00); // User ID. buf.b.position(0); buf.b.limit(buf.size()); buf.b.order(order); }
// constructors public BinaryConnection(ServerId serverId, EndPoint endPoint, ConnectionSettings settings, IStreamFactory streamFactory, IConnectionInitializer connectionInitializer, IEventSubscriber eventSubscriber) { Ensure.IsNotNull(serverId, nameof(serverId)); _endPoint = Ensure.IsNotNull(endPoint, nameof(endPoint)); _settings = Ensure.IsNotNull(settings, nameof(settings)); _streamFactory = Ensure.IsNotNull(streamFactory, nameof(streamFactory)); _connectionInitializer = Ensure.IsNotNull(connectionInitializer, nameof(connectionInitializer)); Ensure.IsNotNull(eventSubscriber, nameof(eventSubscriber)); _backgroundTaskCancellationTokenSource = new CancellationTokenSource(); _backgroundTaskCancellationToken = _backgroundTaskCancellationTokenSource.Token; _connectionId = new ConnectionId(serverId); _receiveLock = new SemaphoreSlim(1); _sendLock = new SemaphoreSlim(1); _state = new InterlockedInt32(State.Initial); _commandEventHelper = new CommandEventHelper(eventSubscriber); eventSubscriber.TryGetEventHandler(out _failedEventHandler); eventSubscriber.TryGetEventHandler(out _closingEventHandler); eventSubscriber.TryGetEventHandler(out _closedEventHandler); eventSubscriber.TryGetEventHandler(out _openingEventHandler); eventSubscriber.TryGetEventHandler(out _openedEventHandler); eventSubscriber.TryGetEventHandler(out _failedOpeningEventHandler); eventSubscriber.TryGetEventHandler(out _receivingMessageEventHandler); eventSubscriber.TryGetEventHandler(out _receivedMessageEventHandler); eventSubscriber.TryGetEventHandler(out _failedReceivingMessageEventHandler); eventSubscriber.TryGetEventHandler(out _sendingMessagesEventHandler); eventSubscriber.TryGetEventHandler(out _sentMessagesEventHandler); eventSubscriber.TryGetEventHandler(out _failedSendingMessagesEvent); }
protected void Test1(IDatagramEventSocket[] sockets, EndPoint[] endPoints) { byte[] sendData = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; int recvIdx = -1, recvSize = -1; byte[] recvData = null; AutoResetEvent done = new AutoResetEvent (false); for (int i = 0; i < sockets.Length; i++) { sockets[i].Bind (endPoints[i]); sockets[i].Received += new DatagramReceiveEventHandler (delegate (object sender, DatagramReceiveEventArgs e) { recvIdx = Array.IndexOf<IDatagramEventSocket> (sockets, sender as IDatagramEventSocket); recvSize = e.Size; recvData = (byte[])e.Buffer.Clone (); done.Set (); }); } for (int i = 0; i < sockets.Length; i++) { for (int k = 0; k < endPoints.Length; k++) { sockets[i].SendTo (sendData, endPoints[k]); done.WaitOne (); Array.Resize<byte> (ref recvData, recvSize); string id = "#" + (i + 1).ToString () + "." + (k + 1).ToString (); Assert.AreEqual (k, recvIdx, id + ".1"); Assert.AreEqual (sendData.Length, recvSize, id + ".2"); Assert.AreEqual (sendData, recvData, id + ".3"); } } }
private void SetupSocket() { if (udpSocket.IsBound) throw new ApplicationException("The socket is already bound and receving."); //recieve data from any source localIPEndPoint = new IPEndPoint(IPAddress.Any, targetPort); localEndPoint = (EndPoint)localIPEndPoint; //init Socket properties: udpSocket.SetSocketOption(SocketOptionLevel.Udp, SocketOptionName.NoDelay, 1); //allow for loopback testing udpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, 1); //extremly important to bind the Socket before joining multicast groups udpSocket.Bind(localIPEndPoint); //set multicast flags, sending flags - TimeToLive (TTL) // 0 - LAN // 1 - Single Router Hop // 2 - Two Router Hops... udpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, udpTTL); //join multicast group udpSocket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(IPAddress.Parse(targetIP))); NotifyMulticastSocketListener(MulticastSocketMessageType.SocketStarted, null); }
public void AddReeiveAlarm(System.Net.EndPoint ep, string server, string communication, string device, IO_PARAALARM alarm, bool result) { if (IOCenterManager.IsBackRun) { return; } //IP // 报警时间 //IO参数 //报警值 //报警类型 //报警等级 //采集站 //通道 //设备 //入库结果 if (!ucEnableAlarm.Checked) { return; } ListViewItem lvi = new ListViewItem(ep.ToString()); lvi.SubItems.Add(alarm.IO_ALARM_DATE); lvi.SubItems.Add(alarm.IO_LABEL + "[" + alarm.IO_NAME + "]"); lvi.SubItems.Add(alarm.IO_ALARM_VALUE); lvi.SubItems.Add(alarm.IO_ALARM_TYPE); lvi.SubItems.Add(alarm.IO_ALARM_LEVEL); lvi.SubItems.Add(server); lvi.SubItems.Add(communication); lvi.SubItems.Add(device); if (result) { lvi.SubItems.Add("入库成功"); } else { lvi.SubItems.Add("入库失败"); } if (listViewAlarm.IsHandleCreated) { listViewAlarm.BeginInvoke(new EventHandler(delegate { try { this.listViewAlarm.Items.Insert(0, lvi); if (this.listViewAlarm.Items.Count > int.Parse(this.cbAlarmSize.SelectedValue)) { this.listViewAlarm.Items.RemoveAt(this.listViewReceive.Items.Count - 1); } } catch { } })); } }
private void CallDisconnected(System.Net.EndPoint from) { if (Disconnected != null) { Task task = new Task(() => Disconnected(from)); task.Start(); } }
private void Calldatareceived(System.Net.EndPoint from, byte[] data, int n) { if (datareceived != null) { Task task = new Task(() => datareceived(from, data, n)); task.Start(); } }
/// <inheritdoc/> public ISession GetSession(System.Net.EndPoint ep) { IPEndPoint ipEP = (IPEndPoint)ep; TLSSession sessionX = FindSession(ipEP); return(sessionX); }
// Send message to the network address private void SendMessage(Data message, System.Net.EndPoint receiver) { byte[] buffer = message.ToBytes(); // Send datagram to the receiver serverSocket.BeginSendTo(buffer, 0, buffer.Length, SocketFlags.None, receiver, new AsyncCallback(OnSend), receiver); }
protected virtual void HandleReceived(byte[] buffer, System.Net.EndPoint endPoint) { if (this._acceptor == null) { base._receiveBuffer.Append(buffer, 0, buffer.Length); this.HandlePackages(); } }
/// <summary> /// 接收UDP数据 /// </summary> /// <param name="memory"></param> /// <param name="endPoint"></param> private async ValueTask Listener_UDPDataHandler(Memory <byte> memory, System.Net.EndPoint endPoint) { if (_appSessions.TryGetValue(endPoint.ToString(), out var appSession)) { var readOnlymemory = (ReadOnlyMemory <byte>)memory; await FilterData(appSession, new ReadOnlySequence <byte>(readOnlymemory)); } }
/// <summary> /// Initializes a UDP channel with the specific endpoint. /// We only support IP endpoints - so throw if it isn't one /// </summary> public UDPChannel(System.Net.EndPoint localEP) { _unicast = SocketSet.Find((IPEndPoint)localEP); if (_unicast != null) { throw new CoAPException("Cannot open the same address twice"); } _unicast = new SocketSet((IPEndPoint)localEP); }
private void FireDataReceived(Byte[] data, System.Net.EndPoint ep, System.Net.EndPoint epLocal, TcpSession tcpSession) { EventHandler <DataReceivedEventArgs> h = DataReceived; if (h != null) { h(this, new DataReceivedEventArgs(data, ep, epLocal, tcpSession)); } }
private void FireDataReceived(byte[] data, System.Net.EndPoint ep) { EventHandler <DataReceivedEventArgs> h = DataReceived; if (h != null) { h(this, new DataReceivedEventArgs(data, ep)); } }
private System.Net.EndPoint recvEP; // Receives the transmitting socket's endpoint /// <summary> /// Constructor. /// </summary> /// <param name="router">The associated message router.</param> public UdpChannel(MsgRouter router) { this.router = router; this.isOpen = false; this.sock = null; this.port = 0; this.recvEP = new IPEndPoint(IPAddress.Any, 0); this.multicastInit = false; this.broadcastClient = null; }
public IAsyncResult BeginConnect(n.EndPoint endpoint, AsyncCallback ac, object st) { n.IPEndPoint ipep = endpoint as n.IPEndPoint; if (endpoint == null) { throw new Exception("Sorry, guy... but this isn't in the scope of this class's purpose."); } attemptedConnectionEndpoint = ipep.Address.ToString(); return(realsocket.BeginConnect(endpoint, ac, st)); }
public IAsyncResult BeginConnect(n.EndPoint endpoint, AsyncCallback callback, object state) { n.IPEndPoint ipep = endpoint as n.IPEndPoint; if (endpoint == null) { throw new ArgumentNullException(nameof(endpoint)); } attemptedConnectionEndpoint = ipep.Address.ToString(); return(realSocket.BeginConnect(endpoint, callback, state)); }
public void ForceDisconnect(System.Net.EndPoint clienttodisconnect) { foreach (ClientData client in clientlist) { if (clienttodisconnect == client.s.RemoteEndPoint) { handledisconnect(client); } } }
protected override bool ConnectInternal(ModuleProc PROC, System.Net.EndPoint remoteEndpoint) { _handler = new TcpClient(AddressFamily.InterNetwork); _handler.SendTimeout = this.SendTimeout; _handler.ReceiveTimeout = this.ReceiveTimeout; _handler.Connect(_remoteEndPoint as IPEndPoint); _localEndPoint = _handler.Client.LocalEndPoint; _socket = _handler.Client; this.WriteSocketLog("has been connected successfully."); return(true); }
private void FireDataReceived(Byte[] data, System.Net.EndPoint ep) { #if LOG_UDP_CHANNEL _Log.Debug(m => m("FireDataReceived: data length={0}", data.Length)); #endif EventHandler <DataReceivedEventArgs> h = DataReceived; if (h != null) { h(this, new DataReceivedEventArgs(data, ep, this)); } }
/// <inheritdoc/> public IEndPoint FindEndPoint(System.Net.EndPoint ep) { foreach (IEndPoint endpoint in _endpoints) { if (endpoint.LocalEndPoint.Equals(ep)) { return(endpoint); } } return(null); }
public void TestInitialize() { clientEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50050); serverEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50060); //easyClient = new EasyClient(); //appServer = new AppServer(); //Assert.IsTrue(appServer.Setup("127.0.0.1", 50060)); //Assert.IsTrue(appServer.Start()); }
// 从EndPoint提取IP地址字符串 private string EndPointToStr(System.Net.EndPoint ePoint) { string IPPoint = ePoint.ToString(); string IPStr = ""; if (IPPoint.IndexOf(":") >= 0) { IPStr = IPPoint.Substring(0, IPPoint.IndexOf(":")); } return(IPStr); }
private void baseListen() { bool flag = true; while (this.isListening) { byte[] array = new byte[63488]; System.Net.EndPoint endPoint = null; try { endPoint = new System.Net.IPEndPoint(this.ipAddress, this.port); this.serverSocket = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Dgram, System.Net.Sockets.ProtocolType.Udp); this.serverSocket.Bind(endPoint); if (flag) { DebugCenter.GetInstance().clearStatusCode(DebugCenter.ST_TrapPortNA, true); flag = false; } this.serverSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveTimeout, 0); int num = this.serverSocket.ReceiveFrom(array, System.Net.Sockets.SocketFlags.None, ref endPoint); if (num > 0 && this.isListening) { string[] separator = new string[] { ":" }; string[] array2 = endPoint.ToString().Split(separator, System.StringSplitOptions.None); SocketMessager socketMessager = new SocketMessager(); socketMessager.Target = array2[0]; socketMessager.Port = System.Convert.ToInt32(array2[1]); socketMessager.DataLenth = num; socketMessager.DataBytes = array; System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(this.waitCallback), socketMessager); } } catch (System.Exception) { try { System.Threading.Thread.Sleep(100); } catch (System.Exception) { } } finally { if (this.serverSocket != null) { this.serverSocket.Close(); } } } }
private async Task <ClusterMessages.ClusterInfo> TryGetGossipFrom(EndPoint gossipSeed) { if (!_gossipClients.TryGetValue(gossipSeed, out var client)) { client = _gossipClientFactory(gossipSeed); _gossipClients[gossipSeed] = client; } var clusterInfoDto = await client.ReadAsync(new Empty()); return(ConvertGrpcClusterInfo(clusterInfoDto)); }
public void AddReeiveDevice(System.Net.EndPoint ep, string datetime, string server, string communication, string device, string msg, bool result) { if (IOCenterManager.IsBackRun) { return; } if (!ucReceive.Checked) { return; } ListViewItem lvi = new ListViewItem(ep.ToString()); lvi.SubItems.Add(datetime); lvi.SubItems.Add(device); lvi.SubItems.Add(communication); lvi.SubItems.Add(server); if (msg.Length > 900) { lvi.SubItems.Add(msg.Substring(0, 900) + "......"); } else { lvi.SubItems.Add(msg); } if (result) { lvi.SubItems.Add("入库成功"); } else { lvi.SubItems.Add("入库失败"); } if (listViewReceive.IsHandleCreated) { listViewReceive.BeginInvoke(new EventHandler(delegate { try { this.listViewReceive.Items.Insert(0, lvi); if (this.listViewReceive.Items.Count > int.Parse(cbReceiveSize.SelectedValue)) { this.listViewReceive.Items.RemoveAt(this.listViewReceive.Items.Count - 1); } } catch { } })); } }
public void Send(byte[] data, System.Net.EndPoint ep) { RawData raw = new RawData(); raw.Data = data; raw.EndPoint = ep; _SendingQueue.Enqueue(raw); if (System.Threading.Interlocked.CompareExchange(ref _Writing, 1, 0) > 0) { return; } BeginSend(); }
public void Add(IPAddress address, byte[] response, System.Net.EndPoint remoteEp) { var result = Message.Parse(response, remoteEp as IPEndPoint, address); if (result != null) { var resultKey = address.ToString(); var targetDict = m_resultMap.GetOrAdd(resultKey, new ConcurrentDictionary <TargetType, ConcurrentDictionary <string, Result> >()); var resultDict = targetDict.GetOrAdd(result.Target.Type, new ConcurrentDictionary <string, Result>()); resultDict.AddOrUpdate(result.Key(), result, (key, value) => result); } }
static void server_Offline(object sender, System.Net.EndPoint client) { IPEndPoint ep = client as IPEndPoint; if (ep != null) { Logs.Create("与客户端[" + ep.Address + "]的连接已断开!"); } if (ClientOffline != null) { ClientOffline(sender, client); } }
private static void Server_OnWriteRequest(ITftpTransfer transfer, System.Net.EndPoint client) { String file = Path.Combine(ServerDirectory, transfer.Filename); if (File.Exists(file)) { CancelTransfer(transfer, TftpErrorPacket.FileAlreadyExists); } else { OutputTransferStatus(transfer, "Accepting write request from " + client); StartTransfer(transfer, new FileStream(file, FileMode.CreateNew)); } }
/// <inheritdoc/> public void Send(Byte[] data, System.Net.EndPoint ep) { RawData raw = new RawData(); raw.Data = data; raw.EndPoint = ep; _sendingQueue.Enqueue(raw); log.Info($"UDP-Enqueued {ep.Serialize()}({data?.Length})"); if (System.Threading.Interlocked.CompareExchange(ref _writing, 1, 0) > 0) { return; } BeginSend(); }
public void OnIPC(System.Net.Sockets.Socket aSocket, System.Net.EndPoint ep, byte[] data) { try { if (data.Length >= 6) { /*string str; * System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding(); * str = enc.GetString(data);*/ string[] ip_s = ep.ToString().Split(':'); Systems.SRX_Serverinfo remoteGameServer = Systems.GetServerByEndPoint(ip_s[0], UInt16.Parse(ip_s[1])); if (remoteGameServer != null) { // decode data //Network.Servers.IPCdeCode(ref data, remoteGameServer.code); Systems.PacketReader pack = new Systems.PacketReader(data); short pcmd = pack.Int16(); if (data.Length >= 6) { switch (pcmd) { default: LogDebug.Show("[IPC] unknown command recevied {0:x}", pcmd); break; } } else { LogDebug.Show("[IPC] data to short"); } } else { LogDebug.Show("[IPC] can't find the GameServer {0}:{1}", ((IPEndPoint)ep).Address.ToString(), ip_s[1]); } } else { LogDebug.Show("[IPC] packet to short from {0}", ep.ToString()); } } catch (Exception ex) { LogDebug.Show("[IPC.OnIPC] {0}", ex); } }