Esempio n. 1
1
    static void Main()
    {
        var sk = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            EndPoint my = new IPEndPoint(IPAddress.Loopback,1233);
            sk.BeginReceiveFrom(new byte[1500], 0, 1500, SocketFlags.None, ref my, new AsyncCallback(ReceiveCallback), null);
            sk.Close();
    }
Esempio n. 2
0
        private static void StartReceivingDataV6()
        {
            if (socketV6 == null)
            {
                return;
            }

            try
            {
                EndPoint endPoint = anyEndPointV6;
                socketV6?.BeginReceiveFrom(receiveBufferV6, 0, MaxUDPPacketSize, SocketFlags.None, ref endPoint, OnReceivedDataV6, socketV6);
            }
            catch (ObjectDisposedException)
            {
                // We can ignore this exception, because this means that we are closing down.
            }
            catch (Exception ex)
            {
                Log.LogErrorException(ex);

                if (socketV6 != null)
                {
                    socketV6.Close();
                    socketV6 = null;
                }
            }
        }
Esempio n. 3
0
        public void StartListeningBroadcast(int port = 42424)
        {
            try
            {
                StopListeningBroadcast();

                _mainUdpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _mainUdpSocket.EnableBroadcast = true;
                _mainUdpSocket.Bind(new IPEndPoint(IPAddress.Any, port));

                var stateObj = new StateObject(_mainUdpSocket);

                EndPoint clientEp = new IPEndPoint(IPAddress.Any, 0);
                _mainUdpSocket?.BeginReceiveFrom(stateObj.buffer, 0, stateObj.buffer.Length, SocketFlags.None, ref clientEp, new AsyncCallback(ReceiveBroadcastCallback), stateObj);
            }
            catch (ObjectDisposedException)
            {
                _gameLogger.Error("Client StartListeningBroadcast: socket has been closed");
            }
            catch (SocketException se)
            {
                _gameLogger.Error($"Client StartListeningBroadcast, socket: {se.ErrorCode}, {se.SocketErrorCode}");
            }
            catch (Exception e)
            {
                _gameLogger.Error($"Client StartListeningBroadcast, unexpected: {e.Message}");
            }
        }
Esempio n. 4
0
	public UDPClient(string serverIP) {
		//Paquete sendData = new Paquete ();
		//sendData.id = 0;
		//sendData.identificadorPaquete = Paquete.Identificador.conectar;
		entrantPackagesCounter = 0;
		sendingPackagesCounter = 0;
		//Creamos conexion
		this.clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
		//Inicializamos IP del servidor
		try{
			IPAddress ipServer = IPAddress.Parse (serverIP);
			IPEndPoint server = new IPEndPoint (ipServer, 30001);
			
			epServer = (EndPoint)server;
			//Debug.Log("Enviando data de inicio de conexion: ");
			//string  data = sendData.GetDataStream();
			//byte[] dataBytes = GetBytes (data);
			//Enviar solicitud de conexion al servidor
			//clientSocket.BeginSendTo (dataBytes,0,dataBytes.Length,SocketFlags.None,epServer,new System.AsyncCallback(this.SendData),null);
			// Inicializando el dataStream
			this.dataStream = new byte[1024];
			// Empezamos a escuhar respuestas del servidor
			clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveData), null);

		}
		catch(FormatException e){
		
			throw e;
		}
		catch(SocketException e){
			
			throw e;
		}
	
	}
Esempio n. 5
0
	public UDPServer()
	{
		try
		{
			// Iniciando array de clientes conectados
			this.listaClientes = new ArrayList();
			entrantPackagesCounter = 0;
			sendingPackagesCounter = 0;			
			// Inicializando el delegado para actualizar estado
			//this.updateStatusDelegate = new UpdateStatusDelegate(this.UpdateStatus);
		
			// Inicializando el socket
			serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
			
			// Inicializar IP y escuhar puerto 30000
			IPEndPoint server = new IPEndPoint(IPAddress.Any, 30001);
			
			// Asociar socket con el IP dado y el puerto
			serverSocket.Bind(server);
			
			// Inicializar IPEndpoint de los clientes
			IPEndPoint clients = new IPEndPoint(IPAddress.Any, 0);
			
			// Inicializar Endpoint de clientes
			EndPoint epSender = (EndPoint)clients;
			
			// Empezar a escuhar datos entrantes
			serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);

		}
		catch (Exception ex)
		{
			//Debug.Log("Error al cargar servidor: " + ex.Message+ " ---UDP ");
		}
	}
Esempio n. 6
0
            public void Receive()
            {
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                Logging.Debug($"++++++Receive Server Port, size:" + _buffer.Length);
                _remote?.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null);
            }
Esempio n. 7
0
 public void StartReceive()
 {
     if (receiveSocket != null)
         StopReceive();
     receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     bindEndPoint = new IPEndPoint(IPAddress.Any, 3001);
     recBuffer = new byte[maxBuffer];
     receiveSocket.Bind(bindEndPoint);
     receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length, SocketFlags.None, ref bindEndPoint, new AsyncCallback(MessageReceivedCallback), (object)this);
 }
    public void Initialize(String _remoteIp, int _remotePort, int _localPort)
    {
        Debug.Log ("UAC CTOR");
        localPort = _localPort;

        remoteIp = _remoteIp;
        remotePort = _remotePort;
        //Setup the socket and message buffer
        udpSock = new Socket (AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        udpSock.Bind (new IPEndPoint (IPAddress.Any, localPort));
        buffer = new byte[1024];

        //Start listening for a new message.
        EndPoint newClientEP = new IPEndPoint (IPAddress.Any, 0);
        udpSock.BeginReceiveFrom (buffer, 0, buffer.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, udpSock);
    }
Esempio n. 9
0
    public void StartReceive()
    {
        try
        {
            if (receiveSocket != null)
                StopReceive();
            receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            bindEndPoint = new IPEndPoint(IPAddress.Any, 3002);

            recBuffer = new byte[maxBuffer];
            receiveSocket.Bind(bindEndPoint);
            receiveSocket.BeginReceiveFrom(recBuffer, 0, recBuffer.Length, SocketFlags.None, ref bindEndPoint, new AsyncCallback(MessageReceivedCallback), (object)this);

        }
        catch (SocketException ex)
        {
            System.Diagnostics.Debug.WriteLine(String.Format("StartReceive SocketException: {0} ", ex.Message));
        }
        catch (Exception ex)
        {
            System.Diagnostics.Debug.WriteLine(String.Format("StartReceive Exception: {0} ", ex.Message));
        }
    }
Esempio n. 10
0
            public SocketUdpServer(IPAddress address, bool dualMode, out int port)
            {
                _server = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                if (dualMode)
                {
                    _server.DualMode = dualMode;
                }

                port = _server.BindToAnonymousPort(address);

                IPAddress remoteAddress = address.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any;
                EndPoint remote = new IPEndPoint(remoteAddress, 0);
                _server.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref remote, Received, null);
            }
Esempio n. 11
0
        private void Receive(System.IAsyncResult ar)
        {
            EndPoint ipe = new IPEndPoint(IPAddress.IPv6Any, 0);

            byte[]     data   = null;
            PacketType msgid  = (PacketType)(-1);
            Packet     packet = null;

            try
            {
                int num = listener.EndReceiveFrom(ar, ref ipe);
                if (num >= 4)
                {
                    data = new byte[num];
                    Buffer.BlockCopy(m_Buffer, 0, data, 0, num);
                    if (BitConverter.ToInt32(data, 0) == data.Length - 4)
                    {
                        packet = new Packet(ipe, data, null);
                        msgid  = packet.BeginRead();
                        packet.ResetPosition();
                    }
                }
                EndPoint remoteEP = new IPEndPoint(IPAddress.IPv6Any, 0);
                listener.BeginReceiveFrom(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, ref remoteEP, Receive, listener);
                if (packet == null)
                {
                    return;
                }
            }
            catch (SocketException e)
            {
                DebugMessage("Server Close On Receive:" + e.ToString());
                Close();
                return;
            }
            catch (Exception e)
            {
                DebugMessage("Receive:" + e.ToString());
                EndPoint remoteEP = new IPEndPoint(IPAddress.IPv6Any, 0);
                listener.BeginReceiveFrom(m_Buffer, 0, m_Buffer.Length, SocketFlags.None, ref remoteEP, Receive, listener);
                return;
            }
            lock (OnListenClient)
            {
                if (OnListenClient.ContainsKey((EndPoint)packet.peer))
                {
                    OnListenClient[(EndPoint)packet.peer].Add(packet);
                    return;
                }
            }
            if (msgid > PacketType.SendAllowTypeTop && msgid < PacketType.SendAllowTypeEnd && ToPeer.ContainsKey((EndPoint)packet.peer))
            {
                PushPacket(packet);
                lock (checklock)
                {
                    clientcheck[(EndPoint)packet.peer] = true;
                }
            }
            else
            {
                switch (msgid)
                {
                case PacketType.ON_CONNECT:
                {
                    ListenClient(packet);
                    break;
                }

                case PacketType.CONNECTION_LOST:
                {
                    if (ToPeer.ContainsKey((EndPoint)packet.peer))
                    {
                        packet.BeginRead();
                        SendData sendData = packet.ReadSendData("");
                        PushPacket(PacketType.CONNECTION_LOST, sendData.DebugMessage, packet.peer);
                    }
                    packet.CloseStream();
                    break;
                }

                case PacketType.P2P_SERVER_CALL:
                {
                    if (ToPeer.ContainsKey((EndPoint)packet.peer))
                    {
                        packet.BeginRead();
                        SendData sendData = packet.ReadSendData(SocketToKey[packet.peer]);

                        string remoteendpoint = (string)((object[])sendData.Parameters)[0];
                        string localendpoint  = (string)((object[])sendData.Parameters)[1];
                        object thedata        = ((object[])sendData.Parameters)[2];

                        if (remoteendpoint != packet.peer.ToString() && ToPeer.TryGetValue(TraceRoute.IPEndPointParse(remoteendpoint, AddressFamily.InterNetworkV6), out PeerBase peer))
                        {
                            ((object[])sendData.Parameters)[0] = packet.peer.ToString();
                            ((object[])sendData.Parameters)[1] = remoteendpoint;
                            using (Packet sendpacket = new Packet(peer.socket))
                            {
                                sendpacket.BeginWrite(PacketType.P2P_SERVER_CALL);
                                sendpacket.WriteSendData(sendData, SocketToKey[TraceRoute.IPEndPointParse(remoteendpoint, AddressFamily.InterNetworkV6)], EncryptAndCompress.LockType.AES);
                                Send(sendpacket, peer.socket);
                            }
                            //DebugMessage(((Client.P2PCode)sendData.Code).ToString() + ":" + packet.peer.ToString() + " to " + remoteendpoint.ToString());
                        }
                        else
                        {
                            ((object[])sendData.Parameters)[1] = packet.peer.ToString();
                            using (Packet sendpacket = new Packet(packet.peer))
                            {
                                sendpacket.BeginWrite(PacketType.P2P_SERVER_FAILED);
                                sendpacket.WriteSendData(sendData, SocketToKey[packet.peer], EncryptAndCompress.LockType.AES);
                                Send(sendpacket, packet.peer);
                            }
                        }
                    }
                    packet.CloseStream();
                    break;
                }

                case PacketType.P2P_GET_PUBLIC_ENDPOINT:
                {
                    using (Packet sendpacket = new Packet(packet.peer))
                    {
                        sendpacket.BeginWrite(PacketType.P2P_GET_PUBLIC_ENDPOINT);
                        sendpacket.WriteSendData(new SendData(0, packet.peer.ToString()), "", EncryptAndCompress.LockType.None);
                        Send(sendpacket, packet.peer);
                    }
                    packet.CloseStream();
                    break;
                }

                case PacketType.CHECK:
                {
                    if (ToPeer.ContainsKey((EndPoint)packet.peer))
                    {
                        lock (checklock)
                        {
                            clientcheck[(EndPoint)packet.peer] = true;
                        }
                    }
                    packet.CloseStream();
                    break;
                }

                case PacketType.ClientDebugMessage:
                {
                    if (ToPeer.ContainsKey((EndPoint)packet.peer))
                    {
                        packet.BeginRead();
                        SendData sendData = packet.ReadSendData(SocketToKey[packet.peer]);
                        DebugMessage("ClientDebugMessage:" + packet.peer.ToString() + " " + sendData.DebugMessage);
                    }

                    packet.CloseStream();
                    break;
                }

                default:
                {
                    DebugMessage(msgid.ToString());
                    //PushPacket(PacketType.CONNECTION_LOST, "不正確的標頭資訊 Receive", packet.peer);
                    packet.CloseStream();
                    break;
                }
                }
            }
        }
Esempio n. 12
0
        private void AsyncBeginReceive()
        {
            // allocate a packet buffer
            //WrappedObject<UDPPacketBuffer> wrappedBuffer = Pool.CheckOut();
            UDPPacketBuffer buf = new UDPPacketBuffer();

            if (!m_shutdownFlag)
            {
                try
                {
                    // kick off an async read
                    m_udpSocket.BeginReceiveFrom(
                        //wrappedBuffer.Instance.Data,
                        buf.Data,
                        0,
                        UDPPacketBuffer.BUFFER_SIZE,
                        SocketFlags.None,
                        ref buf.RemoteEndPoint,
                        AsyncEndReceive,
                        //wrappedBuffer);
                        buf);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.ConnectionReset)
                    {
                        MainConsole.Instance.Warn(
                            "[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " +
                            m_udpPort);
                        bool salvaged = false;
                        while (!salvaged)
                        {
                            try
                            {
                                m_udpSocket.BeginReceiveFrom(
                                    //wrappedBuffer.Instance.Data,
                                    buf.Data,
                                    0,
                                    UDPPacketBuffer.BUFFER_SIZE,
                                    SocketFlags.None,
                                    ref buf.RemoteEndPoint,
                                    AsyncEndReceive,
                                    //wrappedBuffer);
                                    buf);
                                salvaged = true;
                            }
                            catch (SocketException)
                            {
                            }
                            catch (ObjectDisposedException)
                            {
                                return;
                            }
                        }

                        MainConsole.Instance.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
                    }
                }
                catch (ObjectDisposedException)
                {
                }
            }
        }
Esempio n. 13
0
            public void Receive()
            {
                EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);

                _remote.BeginReceiveFrom(_buffer, 0, _buffer.Length, 0, ref remoteEndPoint, new AsyncCallback(RecvFromCallback), null);
            }
Esempio n. 14
0
        private void ReceiveData(IAsyncResult asyncResult)
        {
            try
            {
                byte[] data;
                Packet receivedData = new Packet(serverDataStream);

                Packet     sendData = new Packet();
                IPEndPoint clients  = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender = (EndPoint)clients;
                serverSocket.EndReceiveFrom(asyncResult, ref epSender);
                //Debug.WriteLine(epSender);

                sendData.ChatDataIdentifier = receivedData.ChatDataIdentifier;

                // Username/password split
                switch (receivedData.ChatDataIdentifier)
                {
                case DataIdentifier.LogIn:
                    string[] userPassAux = new string[2];
                    userPassAux           = receivedData.ChatName.Split(':');
                    receivedData.ChatName = userPassAux[0];
                    clientPass            = userPassAux[1];

                    if (!MySqlVerifyClient(receivedData.ChatName, clientPass, epSender.ToString(), mySqlConnection))
                    {
                        sendData.ChatDataIdentifier = receivedData.ChatDataIdentifier = DataIdentifier.FLogIn;
                        sendData.ChatName           = receivedData.ChatName;
                        sendData.ChatMessage        = "Username or Password Incorrect";
                    }

                    data = sendData.GetDataStream();
                    serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epSender, new AsyncCallback(SendData), epSender);
                    serverSocket.BeginReceiveFrom(serverDataStream, 0, serverDataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);
                    break;

                case DataIdentifier.SignUp:
                    if (!MySqlExistentUser(receivedData.ChatName, mySqlConnection))
                    {
                        ClientInfo info    = new ClientInfo();
                        string[]   infoStr = new string[5];
                        infoStr        = receivedData.ChatMessage.Split('%');
                        clientPass     = infoStr[0];
                        info.firstName = infoStr[1];
                        info.lastName  = infoStr[2];
                        info.mail      = infoStr[3];
                        info.phone     = infoStr[4];
                        MySqlAddClient(receivedData.ChatName, clientPass, epSender.ToString(), mySqlConnection, info.firstName, info.lastName, info.mail, info.phone);
                    }
                    else
                    {
                        sendData.ChatDataIdentifier = DataIdentifier.FSignUp;
                    }
                    sendData.ChatName = receivedData.ChatName;
                    data = sendData.GetDataStream();

                    serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epSender, new AsyncCallback(SendData), epSender);

                    serverSocket.BeginReceiveFrom(serverDataStream, 0, serverDataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);
                    break;

                default:
                    sendData.ChatName = receivedData.ChatName;

                    switch (receivedData.ChatDataIdentifier)
                    {
                    case DataIdentifier.Message:
                        sendData.ChatMessage = string.Format("{0} : {1}", receivedData.ChatName, receivedData.ChatMessage);
                        break;

                    case DataIdentifier.Online:
                        Client client = new Client();
                        client.endPoint = epSender;
                        client.name     = receivedData.ChatName;
                        clientList.Add(client);
                        sendData.ChatMessage = string.Format("- {0} is online -", receivedData.ChatName);
                        break;

                    case DataIdentifier.LogOut:
                        foreach (Client c in clientList)
                        {
                            if (c.endPoint.Equals(epSender))
                            {
                                clientList.Remove(c);
                                break;
                            }
                        }
                        sendData.ChatMessage = string.Format("- {0} has gone offline -", receivedData.ChatName);
                        break;
                    }
                    data = sendData.GetDataStream();
                    foreach (Client c in clientList)
                    {
                        if (c.endPoint != epSender || sendData.ChatDataIdentifier != DataIdentifier.Online)
                        {
                            serverSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, c.endPoint, new AsyncCallback(SendData), c.endPoint);
                        }
                    }

                    serverSocket.BeginReceiveFrom(serverDataStream, 0, serverDataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(ReceiveData), epSender);
                    Invoke(updateStatusDelegate, new object[] { sendData.ChatMessage });
                    break;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("ReceiveData Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 15
0
        protected virtual void ConnectWork()
        {
            try
            {
                if (_Url != null)
                {
                    bool isMulticastOrBroadcast = false;
                    int  port = 0;

                    Uri uri = new Uri(_Url);
                    port = uri.Port;
                    var addresses = Dns.GetHostAddresses(uri.DnsSafeHost);
                    if (addresses != null && addresses.Length > 0)
                    {
                        var address = addresses[0];
                        if (address.AddressFamily == AddressFamily.InterNetwork)
                        {
                            if (address.Equals(IPAddress.Broadcast))
                            {
                                isMulticastOrBroadcast = true;
                            }
                            else
                            {
                                var firstb = address.GetAddressBytes()[0];
                                if (firstb >= 224 && firstb < 240)
                                {
                                    isMulticastOrBroadcast = true;
                                }
                            }
                        }
                        else if (address.AddressFamily == AddressFamily.InterNetworkV6)
                        {
                            if (address.IsIPv6Multicast)
                            {
                                isMulticastOrBroadcast = true;
                            }
                        }
                        _Socket = new Socket(address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
                        if (isMulticastOrBroadcast)
                        {
                            _Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
                            if (address.AddressFamily == AddressFamily.InterNetworkV6)
                            {
#if NET_STANDARD_2_0 || NET_4_6
                                // Notice: it is a pitty that unity does not support ipv6 multicast. (Unity 5.6)
                                _Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new IPv6MulticastOption(address));
                                _Socket.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.MulticastTimeToLive, 5);
#endif
                                _Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, 0));
                            }
                            else
                            {
                                if (!address.Equals(IPAddress.Broadcast))
                                {
                                    _Socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new MulticastOption(address, IPAddress.Any));
                                    _Socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 5);
                                }
                                _Socket.Bind(new IPEndPoint(IPAddress.Any, 0));
                            }
                            _BroadcastEP = new IPEndPoint(address, port);
                        }
                        else
                        {
                            _Socket.Connect(address, port);
                        }
                    }
                }
                if (_Socket != null)
                {
                    if (_PreStart != null)
                    {
                        _PreStart(this);
                    }
                    byte[]   receivebuffer = new byte[CONST.MTU];
                    int      receivecnt    = 0;
                    EndPoint broadcastRespEP;
                    if (_BroadcastEP != null && _BroadcastEP.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        broadcastRespEP = new IPEndPoint(IPAddress.IPv6Any, 0);
                    }
                    else
                    {
                        broadcastRespEP = new IPEndPoint(IPAddress.Any, 0);
                    }
                    Action BeginReceive = () =>
                    {
                        if (_BroadcastEP != null)
                        {
                            _Socket.BeginReceiveFrom(receivebuffer, 0, CONST.MTU, SocketFlags.None, ref broadcastRespEP, ar =>
                            {
                                try
                                {
                                    receivecnt = _Socket.EndReceiveFrom(ar, ref broadcastRespEP);
                                }
                                catch (Exception e)
                                {
                                    if (IsConnectionAlive)
                                    {
                                        _ConnectWorkCanceled = true;
                                        PlatDependant.LogError(e);
                                    }
                                }
                                _HaveDataToSend.Set();
                            }, null);
                        }
                        else
                        {
                            _Socket.BeginReceive(receivebuffer, 0, CONST.MTU, SocketFlags.None, ar =>
                            {
                                try
                                {
                                    receivecnt = _Socket.EndReceive(ar);
                                }
                                catch (Exception e)
                                {
                                    if (IsConnectionAlive)
                                    {
                                        _ConnectWorkCanceled = true;
                                        PlatDependant.LogError(e);
                                    }
                                }
                                _HaveDataToSend.Set();
                            }, null);
                        }
                    };
                    if (_OnReceive != null)
                    {
                        BeginReceive();
                    }
                    while (!_ConnectWorkCanceled)
                    {
                        if (_OnReceive != null)
                        {
                            if (receivecnt > 0)
                            {
                                if (_BroadcastEP != null && _WaitForBroadcastResp)
                                {
                                    _OnReceive(receivebuffer, receivecnt, broadcastRespEP);
                                    receivecnt = 0;
                                    BeginReceive();
                                }
                                else
                                {
                                    if (_BroadcastEP != null)
                                    {
                                        _Socket.Connect(broadcastRespEP);
                                        _BroadcastEP = null;
                                    }
                                    _OnReceive(receivebuffer, receivecnt, _Socket.RemoteEndPoint);
                                    receivecnt = 0;
                                    BeginReceive();
                                }
                            }
                        }

                        if (!HoldSending)
                        {
                            BufferInfo binfo;
                            while (_PendingSendMessages.TryDequeue(out binfo))
                            {
                                var message = binfo.Buffer;
                                int cnt     = binfo.Count;
                                if (_OnSend != null && _OnSend(message, cnt))
                                {
                                    if (_OnSendComplete != null)
                                    {
                                        _OnSendComplete(message, true);
                                    }
                                }
                                else
                                {
                                    SendRaw(message, cnt, success =>
                                    {
                                        if (_OnSendComplete != null)
                                        {
                                            _OnSendComplete(message, success);
                                        }
                                    });
                                }
                            }
                        }

                        if (_OnUpdate != null)
                        {
                            _OnUpdate(this);
                        }

                        var waitinterval = _UpdateInterval;
                        var easeratio    = _EaseUpdateRatio;
                        if (waitinterval > 0 && easeratio > 0)
                        {
                            var easeinterval = waitinterval * easeratio;
                            if (_LastSendTick + easeinterval <= System.Environment.TickCount)
                            {
                                waitinterval = easeinterval;
                            }
                        }
                        _HaveDataToSend.WaitOne(waitinterval);
                    }
                }
            }
            catch (ThreadAbortException)
            {
                Thread.ResetAbort();
            }
            catch (Exception e)
            {
                PlatDependant.LogError(e);
            }
            finally
            {
                _ConnectWorkRunning  = false;
                _ConnectWorkCanceled = false;
                if (_PreDispose != null)
                {
                    _PreDispose(this);
                }
                if (_Socket != null)
                {
                    _Socket.Close();
                    _Socket = null;
                }
                // set handlers to null.
                _OnReceive      = null;
                _OnSend         = null;
                _OnSendComplete = null;
                _OnUpdate       = null;
                _PreDispose     = null;
            }
        }
Esempio n. 16
0
 public void StartListening()
 {
     m_signalStop = false;
     m_endPoint   = new IPEndPoint(IPAddress.Any, 0);
     m_socket.BeginReceiveFrom(m_buffer, 0, m_buffer.Length, 0, ref m_endPoint, new AsyncCallback(_onBeginRecieve), m_socket);
 }
Esempio n. 17
0
        /// <summary>
        /// This function performs the actual ping. It sends the ping packets created to
        /// the destination and posts the async receive operation to receive the response.
        /// Once a ping is sent, it waits for the receive handler to indicate a response
        /// was received. If not it times out and indicates this to the user.
        /// </summary>
        public void DoPing()
        {
            // If the packet hasn't already been built, then build it.
            Console.WriteLine("In DoPing() method, do the pinging...");
            Console.WriteLine();
            if (protocolHeaderList.Count == 0)
            {
                BuildPingPacket();
            }

            Console.WriteLine("Pinging {0} with {1} bytes of data ", destEndPoint.Address.ToString(), pingPayloadLength);

            try
            {
                // Post an async receive first to ensure we receive a response to the echo request
                //    in the event of a low latency network.
                pingSocket.BeginReceiveFrom(
                    receiveBuffer,
                    0,
                    receiveBuffer.Length,
                    SocketFlags.None,
                    ref castResponseEndPoint,
                    receiveCallback,
                    this
                    );
                // Keep track of how many outstanding async operations there are
                Interlocked.Increment(ref pingOutstandingReceives);

                // Send an echo request and wait for the response
                while (pingCount > 0)
                {
                    Interlocked.Decrement(ref pingCount);

                    // Increment the sequence count in the ICMP header
                    if (destEndPoint.AddressFamily == AddressFamily.InterNetwork)
                    {
                        icmpHeader.Sequence = (ushort)(icmpHeader.Sequence + (ushort)1);

                        // Build the byte array representing the ping packet. This needs to be done
                        //    before ever send because we change the sequence number (which will affect
                        //    the calculated checksum).
                        pingPacket = icmpHeader.BuildPacket(protocolHeaderList, pingPayload);
                    }
                    else if (destEndPoint.AddressFamily == AddressFamily.InterNetworkV6)
                    {
                        icmpv6EchoRequestHeader.Sequence = (ushort)(icmpv6EchoRequestHeader.Sequence + (ushort)1);

                        // Build the byte array representing the ping packet. This needs to be done
                        //    before ever send because we change the sequence number (which will affect
                        //    the calculated checksum).
                        pingPacket = icmpv6Header.BuildPacket(protocolHeaderList, pingPayload);
                    }

                    // Mark the time we sent the packet
                    pingSentTime = DateTime.Now;

                    // Send the echo request
                    pingSocket.SendTo(pingPacket, destEndPoint);

                    // Wait for the async handler to indicate a response was received
                    if (pingReceiveEvent.WaitOne(pingReceiveTimeout, false) == false)
                    {
                        // timeout occurred
                        Console.WriteLine("Request timed out.");
                    }
                    else
                    {
                        // Reset the event
                        pingReceiveEvent.Reset();
                    }

                    // Sleep for a short time before sending the next request
                    Thread.Sleep(1000);
                }
            }
            catch (SocketException err)
            {
                Console.WriteLine("Socket error occurred: {0}", err.Message);
                throw;
            }
        }
Esempio n. 18
0
        public static void startUDPListening()
        {
            try
            {
                //We are using UDP sockets
                serverSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Dgram, ProtocolType.Udp);
                IPAddress  ip         = IPAddress.Parse(InventoryMSystem.staticClass.strServerIP);
                IPEndPoint ipEndPoint = new IPEndPoint(ip, InventoryMSystem.staticClass.iServePort);
//                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, port);

                //Bind this address to the server
                serverSocket.Bind(ipEndPoint);
                //防止客户端强行中断造成的异常
                long IOC_IN            = 0x80000000;
                long IOC_VENDOR        = 0x18000000;
                long SIO_UDP_CONNRESET = IOC_IN | IOC_VENDOR | 12;

                byte[] optionInValue  = { Convert.ToByte(false) };
                byte[] optionOutValue = new byte[4];
                serverSocket.IOControl((int)SIO_UDP_CONNRESET, optionInValue, optionOutValue);

                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                //The epSender identifies the incoming clients
                EndPoint epSender = (EndPoint)ipeSender;

                //Start receiving data
                serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length,
                                              SocketFlags.None, ref epSender, new AsyncCallback(OnReceive), epSender);


                //TcpListener server = null;
                //try
                //{


                //    // Set the TcpListener on port 13000.
                //    //IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                //    IPAddress localAddr = IPAddress.Parse("192.168.36.168");

                //    // TcpListener server = new TcpListener(port);
                //    server = new TcpListener(localAddr, port);

                //    // Start listening for client requests.
                //    server.Start();

                //    // Buffer for reading data
                //    Byte[] bytes = new Byte[256];
                //    String data = null;

                //    // Enter the listening loop.
                //    while (true)
                //    {
                //        Console.Write("Waiting for a connection... ");

                //        // Perform a blocking call to accept requests.
                //        // You could also user server.AcceptSocket() here.
                //        TcpClient client = server.AcceptTcpClient();
                //        Console.WriteLine("Connected!");

                //        data = null;

                //        // Get a stream object for reading and writing
                //        NetworkStream stream = client.GetStream();

                //        int i;

                //        // Loop to receive all the data sent by the client.
                //        while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                //        {
                //            // Translate data bytes to a ASCII string.
                //            data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
                //            Debug.WriteLine("Received: {0}", data);

                //            // Process the data sent by the client.
                //            data = data.ToUpper();

                //            byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                //            // Send back a response.
                //            stream.Write(msg, 0, msg.Length);
                //            Debug.WriteLine("Sent: {0}", data);
                //        }

                //        // Shutdown and end connection
                //        client.Close();
                //    }
                //}
                //catch (SocketException e)
                //{
                //    Console.WriteLine("SocketException: {0}", e);
                //}
                //finally
                //{
                //    // Stop listening for new clients.
                //    server.Stop();
                //}



                //**********************************************************************
            }
            catch (Exception ex)
            {
                Debug.WriteLine(
                    string.Format("UDPServer.startUDPListening  -> error = {0}"
                                  , ex.Message));
            }
        }
Esempio n. 19
0
        private void button2_Click(object sender, EventArgs e)
        {
            Form5 frm5 = new Form5(this);

            frm5.ShowDialog(this);

            try
            {
                sckt.Bind(epLocal);
                sckt.Connect(epRemote);

                byte[] buffer = new byte[1024];
                sckt.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer);

                if (keyGen == true)
                {
                    RSA          = new RSACryptoServiceProvider(keySize);
                    myPublicKey  = RSA.ExportParameters(false);
                    myPrivateKey = RSA.ExportParameters(true);
                    TextWriter writer    = new StreamWriter(".\\myPublicKey.xml");
                    string     publicKey = RSA.ToXmlString(false);
                    writer.Write(publicKey);
                    writer.Dispose();
                    TextWriter writer2    = new StreamWriter(".\\myPrivateKey.xml");
                    string     privateKey = RSA.ToXmlString(true);
                    writer2.Write(privateKey);
                    writer2.Dispose();

                    System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
                    byte[] msg = new byte[1024];
                    msg = enc.GetBytes(RSA.ToXmlString(false));
                    sckt.Send(msg);
                }

                if (keyGen == false)
                {
                    RSA = new RSACryptoServiceProvider();
                    RSA.FromXmlString(filePrivateKey);
                    myPrivateKey = RSA.ExportParameters(true);
                    TextWriter writer     = new StreamWriter(".\\myPrivateKey.xml");
                    string     privateKey = RSA.ToXmlString(true);
                    writer.Write(privateKey);
                    writer.Close();

                    RSA.FromXmlString(filePublicKey);
                    myPublicKey = RSA.ExportParameters(false);
                    writer      = new StreamWriter(".\\myPublicKey.xml");
                    string publicKey = RSA.ToXmlString(false);
                    writer.Write(publicKey);
                    writer.Close();



                    RSA.FromXmlString(fileForeignKey);
                    foreignPublicKey = RSA.ExportParameters(false);
                    writer           = new StreamWriter(".\\foreignPublicKey.xml");
                    string publicKeyXML = RSA.ToXmlString(false);
                    writer.Write(publicKeyXML);
                    writer.Close();
                    msgCounter = 2;
                }


                button1.Enabled = true;
                szyfrowanieToolStripMenuItem.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Method used in <see cref="_receiverTask"/> to receive Netbios Name Service packets
        /// </summary>
        /// <returns>Task that completes when the <see cref="_receiverTask"/> stops receiving packets</returns>
        private async Task Receive()
        {
            var      buffer        = new byte[RECEIVE_BUFFER_SIZE];
            EndPoint localEndPoint = new IPEndPoint(0, 0);

            while (true)
            {
                var tcs = new TaskCompletionSource <EndPoint>();
                try
                {
                    _socket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref localEndPoint, asynchronousResult =>
                    {
                        var t       = (TaskCompletionSource <EndPoint>)asynchronousResult.AsyncState;
                        EndPoint ep = new IPEndPoint(0, 0);
                        try
                        {
                            _socket.EndReceiveFrom(asynchronousResult, ref ep);
                            t.TrySetResult(ep);
                        }
                        catch (Exception)
                        {
                            t.TrySetResult(null);
                        }
                    }, tcs);
                }
                catch (Exception)
                {
                    if (_endReceive.Task.IsCompleted)
                    {
                        return;
                    }
                    continue;
                }

                // Wait until a new packet has been received or NbNsClient is disposed
                if (await Task.WhenAny(tcs.Task, _endReceive.Task) == _endReceive.Task)
                {
                    return;
                }

                // RemoteEndPoint is null when there was an exception in EndReceive. In that case, discard the packet.
                var remoteEndPoint = (await tcs.Task) as IPEndPoint;
                if (remoteEndPoint == null)
                {
                    continue;
                }

                // If we cannot parse the received packet, discard it.
                NbNsPacketBase packet;
                if (!NbNsPacketBase.TryParse(buffer, out packet))
                {
                    continue;
                }

                // If the received packet is the response to a known request, set the request task result to the received packet.
                var identifier = new PacketIdentifier(packet.Header.NameTrnId, remoteEndPoint.Address);
                TaskCompletionSource <NbNsPacketBase> result;
                if (_pendingUnicastRequests.TryGetValue(identifier, out result))
                {
                    result.TrySetResult(packet);
                }
            }
        }
Esempio n. 21
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                EndPoint receivedFromEP = new IPEndPoint(IPAddress.Any, 0);

                //Get the IP from where we got a message.
                clientSocket.EndReceiveFrom(ar, ref receivedFromEP);

                //Convert the bytes received into an object of type Data.
                Data msgReceived = new Data(byteData);

                //Act according to the received message.
                switch (msgReceived.cmdCommand)
                {
                //We have an incoming call.
                case Command.Invite:
                {
                    if (bIsCallActive == false)
                    {
                        //We have no active call.

                        //Ask the user to accept the call or not.
                        if (MessageBox.Show("Call coming from " + msgReceived.strName + ".\r\n\r\nAccept it?",
                                            "VoiceChat", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            SendMessage(Command.OK, receivedFromEP);
                            vocoder      = msgReceived.vocoder;
                            otherPartyEP = receivedFromEP;
                            otherPartyIP = (IPEndPoint)receivedFromEP;
                            InitializeCall();
                            VideoCall();
                        }
                        else
                        {
                            //Now when The call is declined we Send a busy response to the client.
                            SendMessage(Command.Busy, receivedFromEP);
                        }
                    }
                    else
                    {
                        //Even if We already have an existing call then also we  Send a busy response.
                        SendMessage(Command.Busy, receivedFromEP);
                    }
                    break;
                }

                //OK is received in response to an Invite.
                case Command.OK:
                {
                    Thread init = new Thread(new ThreadStart(InitializeCall));
                    init.IsBackground = true;
                    init.Start();
                    VideoCall();
                    // WriteImage.Start();
                    //  Thread testthread = new Thread(new ThreadStart(VideoCall));
                    // testthread.IsBackground = true;
                    // testthread.Start();

                    // VideoCall();
                    break;
                }

                //The destination is busy.
                case Command.Busy:
                {
                    MessageBox.Show("User busy.", "VoiceChat", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    break;
                }

                case Command.Bye:
                {
                    if (receivedFromEP.Equals(otherPartyEP) == true)
                    {
                        //End the call.
                        UninitializeCall();
                    }
                    break;
                }
                }

                byteData = new byte[1024];
                //Get ready to receive more commands.
                clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref receivedFromEP, new AsyncCallback(OnReceive), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "VoiceChat-OnReceive ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 22
0
        public void VoiceInitialization()
        {
            try
            {
                device = new Device();
                device.SetCooperativeLevel(this, CooperativeLevel.Normal);

                CaptureDevicesCollection captureDeviceCollection = new CaptureDevicesCollection();

                DeviceInformation deviceInfo = captureDeviceCollection[0];

                capture = new Capture(deviceInfo.DriverGuid);

                short channels         = 1;     //Stereo.
                short bitsPerSample    = 16;    //we can either use 8 or 16.
                int   samplesPerSecond = 22050; //11KHz will use 11025 , 22KHz will use 22050, 44KHz use 44100 etc.

                //The waveformat which has to be captured is set here.
                waveFormat                       = new WaveFormat();
                waveFormat.Channels              = channels;
                waveFormat.FormatTag             = WaveFormatTag.Pcm;
                waveFormat.SamplesPerSecond      = samplesPerSecond;
                waveFormat.BitsPerSample         = bitsPerSample;
                waveFormat.BlockAlign            = (short)(channels * (bitsPerSample / (short)8));
                waveFormat.AverageBytesPerSecond = waveFormat.BlockAlign * samplesPerSecond;

                captureBufferDescription             = new CaptureBufferDescription();
                captureBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                captureBufferDescription.Format      = waveFormat;

                playbackBufferDescription             = new BufferDescription();
                playbackBufferDescription.BufferBytes = waveFormat.AverageBytesPerSecond / 5;
                playbackBufferDescription.Format      = waveFormat;
                playbackBuffer = new SecondaryBuffer(playbackBufferDescription, device);

                bufferSize = captureBufferDescription.BufferBytes;

                bIsCallActive  = false;
                nUdpClientFlag = 0;

                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                EndPoint ourEP = new IPEndPoint(IPAddress.Any, 1450);
                //Listen asynchronously on port 1450 for coming messages (Invite, Bye, etc).
                clientSocket.Bind(ourEP);

                //Receive data from any IP.
                EndPoint remoteEP = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));

                byteData = new byte[1024];
                //Here we use technique to receive data asynchronously.
                clientSocket.BeginReceiveFrom(byteData,
                                              0, byteData.Length,
                                              SocketFlags.None,
                                              ref remoteEP,
                                              new AsyncCallback(OnReceive),
                                              null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "dangerVoiceChat-Initialize ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 23
0
        private void OnReceive(IAsyncResult ar)
        {
            try
            {
                IPEndPoint ipeSender = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender  = (EndPoint)ipeSender;

                serverSocket.EndReceiveFrom(ar, ref epSender);

                //Transform the array of bytes received from the user into an
                //intelligent form of object Data
                Data msgReceived = new Data(byteData);

                //We will send this object in response the users request
                Data msgToSend = new Data();

                byte [] message;

                //If the message is to login, logout, or simple text message
                //then when send to others the type of the message remains the same
                msgToSend.cmdCommand = msgReceived.cmdCommand;
                msgToSend.strName    = msgReceived.strName;

                switch (msgReceived.cmdCommand)
                {
                case Command.Login:

                    //When a user logs in to the server then we add her to our
                    //list of clients

                    ClientInfo clientInfo = new ClientInfo();
                    clientInfo.endpoint = epSender;
                    clientInfo.strName  = msgReceived.strName;

                    clientList.Add(clientInfo);

                    //Set the text of the message that we will broadcast to all users
                    msgToSend.strMessage = "<<<" + msgReceived.strName + " has joined the room>>>";
                    break;

                case Command.Logout:

                    //When a user wants to log out of the server then we search for her
                    //in the list of clients and close the corresponding connection

                    int nIndex = 0;
                    foreach (ClientInfo client in clientList)
                    {
                        if (client.endpoint == epSender)
                        {
                            clientList.RemoveAt(nIndex);
                            break;
                        }
                        ++nIndex;
                    }

                    msgToSend.strMessage = "<<<" + msgReceived.strName + " has left the room>>>";
                    break;

                case Command.Message:

                    //Set the text of the message that we will broadcast to all users
                    msgToSend.strMessage = msgReceived.strName + ": " + msgReceived.strMessage;
                    break;

                case Command.List:

                    //Send the names of all users in the chat room to the new user
                    msgToSend.cmdCommand = Command.List;
                    msgToSend.strName    = null;
                    msgToSend.strMessage = null;

                    //Collect the names of the user in the chat room
                    foreach (ClientInfo client in clientList)
                    {
                        //To keep things simple we use asterisk as the marker to separate the user names
                        msgToSend.strMessage += client.strName + "*";
                    }

                    message = msgToSend.ToByte();

                    //Send the name of the users in the chat room
                    serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, epSender,
                                             new AsyncCallback(OnSend), epSender);
                    break;
                }

                if (msgToSend.cmdCommand != Command.List)   //List messages are not broadcasted
                {
                    message = msgToSend.ToByte();

                    foreach (ClientInfo clientInfo in clientList)
                    {
                        if (clientInfo.endpoint != epSender ||
                            msgToSend.cmdCommand != Command.Login)
                        {
                            //Send the message to all users
                            serverSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, clientInfo.endpoint,
                                                     new AsyncCallback(OnSend), clientInfo.endpoint);
                        }
                    }

                    txtLog.Text += msgToSend.strMessage + "\r\n";
                }

                //If the user is logging out then we need not listen from her
                if (msgReceived.cmdCommand != Command.Logout)
                {
                    //Start listening to the message send by the user
                    serverSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epSender,
                                                  new AsyncCallback(OnReceive), epSender);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSServerUDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 24
0
 public void Listen(int Port)
 {
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     try
     {
         socket.Bind(new IPEndPoint(IPAddress.Parse("0"), Port));
         socket.BeginReceiveFrom(ReceiveBuffer, 0, ReceiveBuffer.Length, SocketFlags.None, ref RemoteEP, new AsyncCallback(ReceiveFrom_Callback), socket);
     }
     catch
     {
         if (OnBindFail != null)
         {
             OnBindFail();
         }
     }
 }
Esempio n. 25
0
        private IAsyncResult BeginRecvFrom(AsyncCallback callback, object state)
        {
            var result = _socket.BeginReceiveFrom(_buffer, 0, ushort.MaxValue, SocketFlags.None, ref _remoteEP, callback, state);

            return(result);
        }
Esempio n. 26
0
        private static void ReceiveData(IAsyncResult result)
        {
            System.Text.Encoding iso = System.Text.Encoding.GetEncoding("iso8859-1");
            string dataReceived      = "";

            string[] msgTokens;
            try
            {
                AsyncCallback AcceptReceive    = new AsyncCallback(ReceiveData);
                IPEndPoint    RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, UdpPort);
                EndPoint      tempRemoteEP     = (EndPoint)RemoteIpEndPoint;
                int           numBytes         = soUdp.EndReceiveFrom(result, ref tempRemoteEP);
                dataReceived = iso.GetString(received);

                msgTokens = dataReceived.Split(new char[1] {
                    '!'
                });

                try
                {
                    log.InfoFormat("MSG_FROM_DRV: {0} {1}", msgTokens[0], msgTokens[1].ToString().TrimEnd(new char[] { '\0' }));
                    Console.WriteLine("MSG_FROM_DRV: {0} {1}", msgTokens[0], msgTokens[1].ToString().TrimEnd(new char[] { '\0' }));


                    Vehicle myVehicle = new Vehicle(msgTokens[0]);                     // init vehicle using MID string

                    switch ((MsgDrvType)Enum.Parse(typeof(MsgDrvType), msgTokens[1]))
                    {
                    case MsgDrvType.ARRIVE:
                        log.InfoFormat("Msg ARRIVE {0}", msgTokens[1].ToString().TrimEnd(new char[] { '\0' }));
                        myVehicle.ConfirmArrive();
                        break;

                    case MsgDrvType.DEPART:
                        log.InfoFormat("Msg DEPART {0}", msgTokens[1].ToString().TrimEnd(new char[] { '\0' }));
                        myVehicle.ConfirmDepart();
                        break;

                    case MsgDrvType.SEND_ALL:
                        log.InfoFormat("Msg REQ_ALL {0}", msgTokens[1].ToString().TrimEnd(new char[] { '\0' }));
                        myVehicle.GetAllStops();
                        break;

                    default:
                        break;
                    }
                }
                catch (Exception exc)
                {
                    log.ErrorFormat("Problem with MSG_FROM_DRV: {0}", exc.Message);
                }
                finally
                {
                    soUdp.BeginReceiveFrom(received, 0, received.Length, SocketFlags.None, ref tempRemoteEP, AcceptReceive, null);
                }
            }
            catch (Exception exc)
            {
                log.InfoFormat("Error on UDP socket {0}", exc.Message);
            }
        }
Esempio n. 27
0
        public Form5(FlowLayoutPanel fl, string str1, string str2, string str3, string str4)
        {
            InitializeComponent();

            listMessages.Hide();
            textBox1.Hide();
            textBox3.Hide();
            button1.Hide();
            button2.Hide();
            button3.Hide();
            button4.Hide();
            button5.Hide();


            hSet1  = new HashSet <int>(index1);
            hSet2  = new HashSet <int>(index2);
            hSet3  = new HashSet <int>(index3);
            hSet4  = new HashSet <int>(index4);
            hSet5  = new HashSet <int>(index5);
            hSet6  = new HashSet <int>(index6);
            hSet7  = new HashSet <int>(index7);
            hSet8  = new HashSet <int>(index8);
            hSet9  = new HashSet <int>(index9);
            hSet10 = new HashSet <int>(index10);
            hSet11 = new HashSet <int>(index11);
            hSet12 = new HashSet <int>(index12);



            int n = 25;

            for (int i = 1; i <= n; i++)
            {
                Control[] c = fl.Controls.Find(i.ToString(), false);

                flowLayoutPanel1.Controls.Add(c[0]);
            }



            this.my_ip       = str1;
            this.my_port     = str2;
            this.friend_ip   = str3;
            this.friend_port = str4;



            // MessageBox.Show(my_ip + " " + my_port + " " + friend_ip + " " + friend_port);


            //set up socket
            sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            //get user IP

            //textRemortIP.Text = GetLocalIP();
            my_ip = GetLocalIP();


            try
            {
                epLocal = new IPEndPoint(IPAddress.Parse(my_ip), Convert.ToInt32(my_port.Length));
                sck.Bind(epLocal);

                //connecting to remort IP
                epRemort = new IPEndPoint(IPAddress.Parse(friend_ip), Convert.ToInt32(friend_port.Length));
                sck.Connect(epRemort);

                //Listning to specific port

                buffer = new byte[1500];

                sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemort, new AsyncCallback(MessageCallBack), buffer);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Can't connect");
                return;
            }

            //MessageBox.Show("Connected");


            //MessageBox.Show(flowLayoutPanel1.Size.ToString());
        }
 static void ProcessMeshSignal(IAsyncResult result)
 {
     _meshSignalSocket.BeginReceiveFrom(_signal, 0, 128, SocketFlags.None, ref _ep, new AsyncCallback(Program.ProcessMeshSignal), new object());
 }
Esempio n. 29
0
        public void NetworkTargetUdpTest()
        {
            var target = new NetworkTarget()
            {
                Address        = "udp://127.0.0.1:3002",
                Layout         = "${message}\n",
                KeepConnection = true,
            };

            string expectedResult = string.Empty;

            using (var listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
            {
                Exception receiveException = null;
                var       receivedMessages = new List <string>();
                var       receiveFinished  = new ManualResetEvent(false);

                byte[] receiveBuffer = new byte[4096];

                listener.Bind(new IPEndPoint(IPAddress.Loopback, 3002));
                EndPoint      remoteEndPoint   = null;
                AsyncCallback receivedDatagram = null;

                receivedDatagram = result =>
                {
                    try
                    {
                        int    got     = listener.EndReceiveFrom(result, ref remoteEndPoint);
                        string message = Encoding.UTF8.GetString(receiveBuffer, 0, got);
                        lock (receivedMessages)
                        {
                            receivedMessages.Add(message);
                            if (receivedMessages.Count == 100)
                            {
                                receiveFinished.Set();
                            }
                        }

                        remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                        listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);
                    }
                    catch (Exception ex)
                    {
                        receiveException = ex;
                    }
                };

                remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                listener.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, receivedDatagram, null);

                target.Initialize(new LoggingConfiguration());

                int pendingWrites  = 100;
                var writeCompleted = new ManualResetEvent(false);
                var exceptions     = new List <Exception>();

                AsyncContinuation writeFinished =
                    ex =>
                {
                    lock (exceptions)
                    {
                        exceptions.Add(ex);
                        pendingWrites--;
                        if (pendingWrites == 0)
                        {
                            writeCompleted.Set();
                        }
                    }
                };

                int toWrite = pendingWrites;
                for (int i = 0; i < toWrite; ++i)
                {
                    var ev = new LogEventInfo(LogLevel.Info, "logger1", "message" + i).WithContinuation(writeFinished);
                    target.WriteAsyncLogEvent(ev);
                    expectedResult += "message" + i + "\n";
                }

                Assert.IsTrue(writeCompleted.WaitOne(10000, false));
                target.Close();
                Assert.IsTrue(receiveFinished.WaitOne(10000, false));
                Assert.AreEqual(toWrite, receivedMessages.Count);
                for (int i = 0; i < toWrite; ++i)
                {
                    Assert.IsTrue(receivedMessages.Contains("message" + i + "\n"), "Message #" + i + " not received.");
                }

                Assert.IsNull(receiveException, "Receive exception: " + receiveException);
            }
        }
Esempio n. 30
0
 public IAsyncResult BeginReceiveFrom(byte[] buffer, int offset, int size, SocketFlags socketFlags, ref EndPoint remoteEP, AsyncCallback callback, object state)
 {
     return(m_ClientSocket.BeginReceiveFrom(buffer, offset, size, socketFlags, ref remoteEP, callback, state));
 }
Esempio n. 31
0
 /// <summary>
 /// Begin an asynchronous receive of the next bit of raw data
 /// </summary>
 protected virtual void BeginReceive()
 {
     m_socket.BeginReceiveFrom(
         RecvBuffer, 0, RecvBuffer.Length, SocketFlags.None, ref reusedEpSender, ReceivedData, null);
 }
Esempio n. 32
0
        private void ReceiveData(IAsyncResult asyncResult)
        {
            try
            {
                Packet     receivedData = new Packet(this.dataStream);
                IPEndPoint clients      = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   epSender     = (EndPoint)clients;
                serverSocket.EndReceiveFrom(asyncResult, ref epSender);
                switch (receivedData.ChatDataIdentifier)
                {
                case DataIdentifier.Message:
                    DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(Data));
                    MemoryStream ms   = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(receivedData.ChatMessage));
                    Data         draw = (Data)js.ReadObject(ms);

                    x  = Convert.ToInt32(draw.X * kWidth);
                    y  = Convert.ToInt32(draw.Y * kHeight);
                    x0 = Convert.ToInt32(draw.X0 * kWidth);
                    y0 = Convert.ToInt32(draw.Y0 * kHeight);
                    cx = Convert.ToInt32(draw.Cx * kWidth);
                    cy = Convert.ToInt32(draw.Cy * kHeight);

                    Pen pen = new Pen(Color.Blue);
                    pen.Width = draw.PenSize;
                    pen.Color = draw.Color;
                    switch (draw.DrawMode)
                    {
                    case 1:
                    {
                        graphics.DrawLine(pen, x0, y0, x, y);
                        break;
                    }

                    case 2:
                    {
                        graphics.DrawEllipse(pen, x0, y0, cx, cy);
                        break;
                    }

                    case 3:
                    {
                        if (cx >= 0 && cy >= 0)
                        {
                            graphics.DrawRectangle(pen, x0, y0, cx, cy);
                        }
                        else if (cx >= 0 && cy <= 0)
                        {
                            graphics.DrawRectangle(pen, x0, y0 + cy, cx, -1 * cy);
                        }
                        else if (cx <= 0 && cy >= 0)
                        {
                            graphics.DrawRectangle(pen, x0 + cx, y0, -1 * cx, cy);
                        }
                        else if (cx <= 0 && cy <= 0)
                        {
                            graphics.DrawRectangle(pen, x0 + cx, y0 + cy, -1 * cx, -1 * cy);
                        }
                        break;
                    }

                    case 4:
                    {
                        SolidBrush Brush = new SolidBrush(draw.Color);
                        if (cx >= 0 && cy >= 0)
                        {
                            graphics.FillRectangle(Brush, x0, y0, cx, cy);
                        }
                        else if (cx >= 0 && cy <= 0)
                        {
                            graphics.FillRectangle(Brush, x0, y0 + cy, cx, -1 * cy);
                        }
                        else if (cx <= 0 && cy >= 0)
                        {
                            graphics.FillRectangle(Brush, x0 + cx, y0, -1 * cx, cy);
                        }
                        else if (cx <= 0 && cy <= 0)
                        {
                            graphics.FillRectangle(Brush, x0 + cx, y0 + cy, -1 * cx, -1 * cy);
                        }
                        break;
                    }

                    case 5:
                    {
                        SolidBrush Brush = new SolidBrush(draw.Color);
                        graphics.FillEllipse(Brush, x0, y0, cx, cy);
                        break;
                    }

                    case 6:
                    {
                        //////////////
                        break;
                    }
                    }
                    IntPtr   desktopDC = GetDC(IntPtr.Zero);
                    Graphics g         = Graphics.FromHdc(desktopDC);
                    g.DrawImage(bitmap, 0, 0);
                    g.Dispose();
                    ReleaseDC(desktopDC);
                    ms.Close();
                    break;
                }
                serverSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epSender, new AsyncCallback(this.ReceiveData), epSender);
            }
            catch (Exception ex)
            {
                MessageBox.Show("ReceiveData Error: " + ex.Message, "UDP Server", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 33
0
        private void BeginReceiveFrom_Helper(IPAddress listenOn, IPAddress connectTo, bool expectedToTimeout = false)
        {
            using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                serverSocket.ReceiveTimeout = 500;
                int port = serverSocket.BindToAnonymousPort(listenOn);

                EndPoint receivedFrom = new IPEndPoint(connectTo, port);
                IAsyncResult async = serverSocket.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref receivedFrom, null, null);

                // Behavior difference from Desktop: receivedFrom will _not_ change during the synchronous phase.

                // IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
                // Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                // Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);

                SocketUdpClient client = new SocketUdpClient(_log, serverSocket, connectTo, port);
                bool success = async.AsyncWaitHandle.WaitOne(expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout);
                if (!success)
                {
                    throw new TimeoutException();
                }

                receivedFrom = new IPEndPoint(connectTo, port);
                int received = serverSocket.EndReceiveFrom(async, ref receivedFrom);

                Assert.Equal(1, received);
                Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint));

                IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
                Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);
            }
        }
Esempio n. 34
0
        private void ReceiveCallback(IAsyncResult ar)
        {
            SSUSession session = null;

            try
            {
                EndPoint ep   = RemoteEP;
                var      size = MySocket.EndReceiveFrom(ar, ref ep);

                if (ep.AddressFamily != AddressFamily.InterNetwork &&
                    (!SessionLayer.RouterContext.Inst.UseIpV6 ||
                     ep.AddressFamily != AddressFamily.InterNetworkV6))
                {
                    return;         // TODO: Add IPV6
                }
                if (size <= 37)
                {
                    Logging.LogDebugData($"SSU Recv: {size} bytes [0x{size:X}] from {ep} (hole punch, ignored)");
                    return;
                }

                var sessionendpoint = (IPEndPoint)ep;

                Logging.LogDebugData($"SSU Recv: {size} bytes [0x{size:X}] from {ep}");

                lock ( Sessions )
                {
                    if (!Sessions.ContainsKey(sessionendpoint))
                    {
                        if (IPFilter.IsFiltered(((IPEndPoint)ep).Address))
                        {
                            Logging.LogTransport($"SSUHost ReceiveCallback: IPAddress {sessionendpoint} is blocked. {size} bytes.");
                            return;
                        }

                        ++IncommingConnectionAttempts;

                        Logging.LogTransport($"SSUHost: incoming connection " +
                                             $"from {sessionendpoint} created.");

                        session = new SSUSession(
                            this,
                            Send,
                            (IPEndPoint)ep,
                            MyRouterContext);

                        Sessions[sessionendpoint] = session;

                        Logging.LogTransport($"SSUHost: incoming connection " +
                                             $"{session.DebugId} from {sessionendpoint} created.");

                        NeedCpu(session);
                        ConnectionCreated?.Invoke(session);
                    }
                    else
                    {
                        session = Sessions[sessionendpoint];
                    }
                }

                var localbuffer = BufRefLen.Clone(ReceiveBuf, 0, size);

#if DEBUG
                Stopwatch Stopwatch1 = new Stopwatch();
                Stopwatch1.Start();
#endif
                try
                {
                    session.Receive(localbuffer);
                }
                catch (ThreadAbortException taex)
                {
                    AddFailedSession(session);
                    Logging.Log(taex);
                }
                catch (ThreadInterruptedException tiex)
                {
                    AddFailedSession(session);
                    Logging.Log(tiex);
                }
                catch (ChecksumFailureException cfex)
                {
                    AddFailedSession(session);
                    Logging.Log(cfex);
                }
                catch (SignatureCheckFailureException scex)
                {
                    AddFailedSession(session);
                    Logging.Log(scex);
                }
                catch (FailedToConnectException fcex)
                {
                    AddFailedSession(session);
#if LOG_MUCH_TRANSPORT
                    Logging.LogTransport(fcex);
#endif
                    if (session != null)
                    {
                        NetDb.Inst.Statistics.FailedToConnect(session.RemoteRouterIdentity.IdentHash);
                        session.RaiseException(fcex);
                    }
                }
#if DEBUG
                Stopwatch1.Stop();
                if (Stopwatch1.ElapsedMilliseconds > SessionCallWarningLevelMilliseconds)
                {
                    Logging.LogTransport(
                        $"SSUHost ReceiveCallback: WARNING Session {session} used {Stopwatch1.ElapsedMilliseconds}ms cpu.");
                }
#endif
            }
            catch (Exception ex)
            {
                AddFailedSession(session);
                Logging.Log(ex);

                if (session != null && session.RemoteRouterIdentity != null && NetDb.Inst != null)
                {
                    NetDb.Inst.Statistics.DestinationInformationFaulty(session.RemoteRouterIdentity.IdentHash);
                    session.RaiseException(ex);
                }
            }
            finally
            {
                RemoteEP = LocalEP;
                MySocket.BeginReceiveFrom(ReceiveBuf, 0, ReceiveBuf.Length, SocketFlags.None, ref RemoteEP,
                                          new AsyncCallback(ReceiveCallback), MySocket);
            }
        }
Esempio n. 35
0
        [Fact] // Base case
        // "The supplied EndPoint of AddressFamily InterNetwork is not valid for this Socket, use InterNetworkV6 instead."
        public void Socket_BeginReceiveFromV4IPEndPointFromV4Client_Throws()
        {
            Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            socket.DualMode = false;

            EndPoint receivedFrom = new IPEndPoint(IPAddress.Loopback, UnusedPort);
            Assert.Throws<ArgumentException>(() =>
            {
                socket.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref receivedFrom, null, null);
            });
        }
Esempio n. 36
0
        private void BeginReceiveFrom_Helper(IPAddress listenOn, IPAddress connectTo)
        {
            using (Socket serverSocket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                serverSocket.ReceiveTimeout = 500;
                int port = serverSocket.BindToAnonymousPort(listenOn);

                EndPoint receivedFrom = new IPEndPoint(connectTo, port);
                IAsyncResult async = serverSocket.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref receivedFrom, null, null);

                IPEndPoint remoteEndPoint = receivedFrom as IPEndPoint;
                Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);

                SocketUdpClient client = new SocketUdpClient(serverSocket, connectTo, port);
                bool success = async.AsyncWaitHandle.WaitOne(500);
                if (!success)
                {
                    throw new TimeoutException();
                }

                receivedFrom = new IPEndPoint(connectTo, port);
                int received = serverSocket.EndReceiveFrom(async, ref receivedFrom);

                Assert.Equal(1, received);
                Assert.Equal<Type>(receivedFrom.GetType(), typeof(IPEndPoint));

                remoteEndPoint = receivedFrom as IPEndPoint;
                Assert.Equal(AddressFamily.InterNetworkV6, remoteEndPoint.AddressFamily);
                Assert.Equal(connectTo.MapToIPv6(), remoteEndPoint.Address);
            }
        }
Esempio n. 37
0
        private void AsyncBeginReceive()
        {
            UDPPacketBuffer buf;

            // FIXME: Disabled for now as this causes issues with reused packet objects interfering with each other
            // on Windows with m_asyncPacketHandling = true, though this has not been seen on Linux.
            // Possibly some unexpected issue with fetching UDP data concurrently with multiple threads.  Requires more investigation.
//            if (UsePools)
//                buf = Pool.GetObject();
//            else
            buf = new UDPPacketBuffer();

            if (IsRunningInbound)
            {
                try
                {
                    // kick off an async read
                    m_udpSocket.BeginReceiveFrom(
                        //wrappedBuffer.Instance.Data,
                        buf.Data,
                        0,
                        UDPPacketBuffer.BUFFER_SIZE,
                        SocketFlags.None,
                        ref buf.RemoteEndPoint,
                        AsyncEndReceive,
                        //wrappedBuffer);
                        buf);
                }
                catch (SocketException e)
                {
                    if (e.SocketErrorCode == SocketError.ConnectionReset)
                    {
                        m_log.Warn("[UDPBASE]: SIO_UDP_CONNRESET was ignored, attempting to salvage the UDP listener on port " + m_udpPort);
                        bool salvaged = false;
                        while (!salvaged)
                        {
                            try
                            {
                                m_udpSocket.BeginReceiveFrom(
                                    //wrappedBuffer.Instance.Data,
                                    buf.Data,
                                    0,
                                    UDPPacketBuffer.BUFFER_SIZE,
                                    SocketFlags.None,
                                    ref buf.RemoteEndPoint,
                                    AsyncEndReceive,
                                    //wrappedBuffer);
                                    buf);
                                salvaged = true;
                            }
                            catch (SocketException) { }
                            catch (ObjectDisposedException) { return; }
                        }

                        m_log.Warn("[UDPBASE]: Salvaged the UDP listener on port " + m_udpPort);
                    }
                }
                catch (ObjectDisposedException e)
                {
                    m_log.Error(
                        string.Format("[UDPBASE]: Error processing UDP begin receive {0}.  Exception  ", UdpReceives), e);
                }
                catch (Exception e)
                {
                    m_log.Error(
                        string.Format("[UDPBASE]: Error processing UDP begin receive {0}.  Exception  ", UdpReceives), e);
                }
            }
        }
Esempio n. 38
0
 private static void BeginReceiveFrom()
 {
     icmpSocket.BeginReceiveFrom(receiveBuffer, 0, receiveBuffer.Length, SocketFlags.None, ref remoteEndPoint, ReceiveCallback, null);
 }
Esempio n. 39
0
        public void UdpReceiveData(IAsyncResult iar)
        {
            try
            {
                String sGPS;

                // Create temporary remote end Point
                IPEndPoint sender       = new IPEndPoint(IPAddress.Any, 0);
                EndPoint   tempRemoteEP = (EndPoint)sender;

                // Get the Socket
                TCPSockets tcpSockets = (TCPSockets)iar.AsyncState;
                Socket     remote     = tcpSockets.socketUDP;

                // Call EndReceiveFrom to get the received Data
                int nBytesRec = remote.EndReceiveFrom(iar, ref tempRemoteEP);

                if (nBytesRec > 0)
                {
                    sGPS = System.Text.Encoding.ASCII.GetString(tcpSockets.byTcpBuffer, 0, nBytesRec);

                    try
                    {
                        if (m_GpsTracker.m_MessageMonitor != null)
                        {
                            m_GpsTracker.m_MessageMonitor.AddMessageTCPUDPRaw(sGPS);
                        }
                    }
                    catch (Exception)
                    {
                        m_GpsTracker.m_MessageMonitor = null;
                    }



                    tcpSockets.sStream += sGPS;
                    int     iIndex = -1;
                    char [] cEOL   = { '\n', '\r' };
                    string  sData  = "";
                    do
                    {
                        iIndex = tcpSockets.sStream.IndexOfAny(cEOL);
                        if (iIndex >= 0)
                        {
                            sData = tcpSockets.sStream.Substring(0, iIndex);
                            sData = sData.Trim(cEOL);
                            tcpSockets.sStream = tcpSockets.sStream.Remove(0, iIndex + 1);

                            if (sData != "")
                            {
                                m_GpsTracker.ShowGPSIcon(sData.ToCharArray(), sData.Length, false, tcpSockets.iDeviceIndex, false, true, 0, 0);
                            }
                        }
                    }while(iIndex >= 0);
                }

                GPSSource gpsSource = (GPSSource)m_GpsTracker.m_gpsSourceList[tcpSockets.iDeviceIndex];
                EndPoint  endPoint  = new IPEndPoint(IPAddress.Any, Convert.ToInt32(gpsSource.iUDPPort));
                remote.BeginReceiveFrom(tcpSockets.byTcpBuffer, 0, 1024, SocketFlags.None, ref endPoint, new AsyncCallback(UdpReceiveData), tcpSockets);
            }
            catch (Exception)
            {
            }
        }
Esempio n. 40
0
        // "The parameter remoteEP must not be of type DnsEndPoint."
        public void Socket_BeginReceiveFromDnsEndPoint_Throws()
        {
            using (Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                int port = socket.BindToAnonymousPort(IPAddress.IPv6Loopback);
                EndPoint receivedFrom = new DnsEndPoint("localhost", port, AddressFamily.InterNetworkV6);

                Assert.Throws<ArgumentException>(() =>
                {
                    socket.BeginReceiveFrom(new byte[1], 0, 1, SocketFlags.None, ref receivedFrom, null, null);
                });
            }
        }
Esempio n. 41
0
        private void Run()
        {
            var buf  = new byte[65536];
            var buf2 = new byte[65536];

            try
            {
                MulticastSocket.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref MLEp, new AsyncCallback(ReceiveMulticast), buf);

                DiscoverDevices();
                Thread.Sleep(1000);
                while (!Terminated)
                {
                    try
                    {
                        DiscoverAction.Do(DiscoverDevices);

                        GetExternalAddressAction.Do(delegate
                        {
                            if (GetExternalAddressAction.Frequency.ToSeconds < 1.0)
                            {
                                GetExternalAddressAction.Frequency = TickSpan.Seconds(60 * 30);
                                GetExternalAddressAction.Start();
                            }

                            if (WANIPConnectionsCtlInfo.Count > 0)
                            {
                                ControlInfo ci;
                                lock ( WANIPConnectionsCtlInfo )
                                {
                                    ci = WANIPConnectionsCtlInfo.Values.First();
                                }
                                RequestExternalIpAddress(ci);
                            }
                        });

                        ExternalPortMappingAction.Do(delegate
                        {
                            if (ExternalPortMappingAction.Frequency.ToSeconds < 1.0)
                            {
                                ExternalPortMappingAction.Frequency = TickSpan.Seconds(LeaseMapDurationSeconds - 200);
                                ExternalPortMappingAction.Start();
                            }

                            if (WANIPConnectionsCtlInfo.Count > 0)
                            {
                                UpdatePortMapping("TCP");
                                UpdatePortMapping("UDP");
                            }
                        });

                        Thread.Sleep(1000);
                    }
                    catch (ThreadAbortException ex)
                    {
                        Logging.Log(ex);
                    }
                    catch (Exception ex)
                    {
                        Logging.Log(ex);
                    }
                }
            }
            finally
            {
                Terminated = true;
            }
        }
Esempio n. 42
0
        public void BeginReceiveFrom_NotSupported()
        {
            using (Socket sock = new Socket(SocketType.Dgram, ProtocolType.Udp))
            {
                EndPoint ep = new IPEndPoint(IPAddress.Any, 0);
                sock.Bind(ep);

                byte[] buf = new byte[1];

                Assert.Throws<PlatformNotSupportedException>(() => sock.BeginReceiveFrom(buf, 0, buf.Length, SocketFlags.None, ref ep, null, null));
            }
        }
Esempio n. 43
0
        /// <summary>
        /// Starts receiving data.
        /// </summary>
        /// <exception cref="ObjectDisposedException">Is raised when this calss is disposed and this method is accessed.</exception>
        public void Start()
        {
            if (m_IsDisposed)
            {
                throw new ObjectDisposedException(this.GetType().Name);
            }
            if (m_IsRunning)
            {
                return;
            }
            m_IsRunning = true;

            bool isIoCompletionSupported = Net_Utils.IsSocketAsyncSupported();

            m_pEventArgs = new UDP_e_PacketReceived();
            m_pBuffer    = new byte[m_BufferSize];

            if (isIoCompletionSupported)
            {
                m_pSocketArgs = new SocketAsyncEventArgs();
                m_pSocketArgs.SetBuffer(m_pBuffer, 0, m_BufferSize);
                m_pSocketArgs.RemoteEndPoint = new IPEndPoint(m_pSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
                m_pSocketArgs.Completed     += delegate(object s1, SocketAsyncEventArgs e1){
                    if (m_IsDisposed)
                    {
                        return;
                    }

                    try{
                        if (m_pSocketArgs.SocketError == SocketError.Success)
                        {
                            OnPacketReceived(m_pBuffer, m_pSocketArgs.BytesTransferred, (IPEndPoint)m_pSocketArgs.RemoteEndPoint);
                        }
                        else
                        {
                            OnError(new Exception("Socket error '" + m_pSocketArgs.SocketError + "'."));
                        }

                        IOCompletionReceive();
                    }
                    catch (Exception x) {
                        OnError(x);
                    }
                };
            }

            // Move processing to thread pool.
            ThreadPool.QueueUserWorkItem(delegate(object state){
                if (m_IsDisposed)
                {
                    return;
                }

                try{
                    if (isIoCompletionSupported)
                    {
                        IOCompletionReceive();
                    }
                    else
                    {
                        EndPoint rtpRemoteEP = new IPEndPoint(m_pSocket.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, 0);
                        m_pSocket.BeginReceiveFrom(
                            m_pBuffer,
                            0,
                            m_BufferSize,
                            SocketFlags.None,
                            ref rtpRemoteEP,
                            new AsyncCallback(this.AsyncSocketReceive),
                            null
                            );
                    }
                }
                catch (Exception x) {
                    OnError(x);
                }
            });
        }