Esempio n. 1
0
 private void BroadcastCallback(IAsyncResult ar)
 {
     try
     {
         int len = broadcaster.EndSendTo(ar);
         lock (bcStopLock)
         {
             if (isBCStop)
             {
                 return;
             }
         }
         if (len == bcBuf.Length)
         {
             //wait a moment
             Thread.Sleep(BROADCAST_INTERVAL);
         }
         broadcaster?.BeginSendTo(bcBuf, 0, bcBuf.Length, SocketFlags.None,
                                  bcEP, new AsyncCallback(BroadcastCallback), null);
     }
     catch (Exception e)
     {
         Logging.Error(e);
     }
 }
 public void SendTo(byte[] dataBuf, IPEndPoint targetEP)
 {
     try
     {
         udpSocket?.BeginSendTo(dataBuf, 0, dataBuf.Length, SocketFlags.None,
                                targetEP, new AsyncCallback(SendToCallback), targetEP);
     }
     catch (Exception e)
     {
         Logging.Error(e);
     }
 }
Esempio n. 3
0
 public Result BroadcastMessage(byte[] message)
 {
     try
     {
         _mainUdpSocket?.BeginSendTo(message, 0, message.Length, SocketFlags.None, udpClientEP, new AsyncCallback(UdpSendCallback), _mainUdpSocket);
         return(Result.Ok());
     }
     catch (ObjectDisposedException)
     {
         return(Result.Fail("Server BroadcastMessage: socket has been closed"));
     }
     catch (SocketException se)
     {
         return(Result.Fail($"Server BroadcastMessage, socket: [{se.ErrorCode}], [{se.SocketErrorCode}] - {se.Message}"));
     }
     catch (Exception e)
     {
         return(Result.Fail($"Server BroadcastMessage, unexpected: {e.Message}"));
     }
 }
Esempio n. 4
0
        //Send the string out to server
        private void SendNMEA()
        {
            try
            {
                // Get packet as byte array
                byte[] byteData = Encoding.ASCII.GetBytes(sbSendText.ToString());

                if (byteData.Length != 0)
                {
                    // Send packet to the server
                    clientSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epServer, new AsyncCallback(SendData), null);
                }

                //not really necessary but does show what was in buffer that was sent
                txtNMEA.Text = (Encoding.ASCII.GetString(byteData));
            }
            catch (Exception ex)
            {
                MessageBox.Show("Send Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }            // Check we are connected
        }
Esempio n. 5
0
        /*
         * Send a message to the remote party.
         */
        private void SendMessage(Command cmd, EndPoint sendToEP)
        {
            try
            {
                //Create the message to send.
                Data msgToSend = new Data();

                msgToSend.strName    = Globals.currentUserLogin; //txtName.Text;   //Name of the user.
                msgToSend.cmdCommand = cmd;                      //Message to send.


                byte[] message = msgToSend.ToByte();

                //Send the message asynchronously.
                clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP, new AsyncCallback(OnSend), null);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "VoiceChat-SendMessage ()", MessageBoxButton.OK, MessageBoxImage.Error, MessageBoxResult.OK);
            }
        }
Esempio n. 6
0
 public void Send(IPEndPoint address, byte[] data, bool async = true)
 {
     try {
         if (async)
         {
             fSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, address, (ar) => {
                 try {
                     fSocket.EndSendTo(ar);
                 } catch (Exception ex) {
                     fLogger.WriteError("Send.1(" + address + ")", ex);
                 }
             }, null);
         }
         else
         {
             fSocket.SendTo(data, 0, data.Length, SocketFlags.None, address);
         }
     } catch (Exception ex) {
         fLogger.WriteError("Send()", ex);
     }
 }
Esempio n. 7
0
        private void sendBtn_Click(object sender, EventArgs e)
        {
            try
            {
                Packet sendData = new Packet();
                sendData.ChatName           = clientName;
                sendData.ChatMessage        = messageText.Text.Trim();
                sendData.ChatDataIdentifier = DataIdentifier.Message;

                byte[] byteData = sendData.GetDataStream();
                clientSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, serverEp, new AsyncCallback(SendData), null);
                messageText.Text = string.Empty;
            }
            catch (ObjectDisposedException ex)
            {
            }
            catch (Exception ex)
            {
                MessageBox.Show("Send Error : " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Sends a Netbios Name Service packet asynchronously
        /// </summary>
        /// <param name="packet">Netbios Name Service packet to send</param>
        /// <param name="address">Target address to send the packet to</param>
        /// <param name="timeOutMilliseconds">
        /// Maximum time in milliseconds to wait for the send operation to finish. If it takes longer, the target IP address
        /// most likely does not exist in a local subnet (although the address is part of a local subnet) so that the ARP
        /// protocol is not able to find the MAC address for the given IP address.
        /// </param>
        /// <returns>
        /// A <see cref="Task"/> that completes with result = <c>true</c> when the packet was successfully sent or
        /// with result = <c>false</c> if the send operation was not successful witin the given timeout.
        /// </returns>
        public async Task <bool> SendPacketAsync(NbNsPacketBase packet, IPAddress address, int timeOutMilliseconds = SEND_TIMEOUT)
        {
            if (packet == null)
            {
                throw new ArgumentNullException("packet");
            }
            if (address == null)
            {
                throw new ArgumentNullException("address");
            }
            var endPoint = new IPEndPoint(address, TARGET_PORT);
            var tcs      = new TaskCompletionSource <int>();

            try
            {
                _socket.BeginSendTo(packet, 0, packet.Length, SocketFlags.None, endPoint, asynchronousResult =>
                {
                    var t = (TaskCompletionSource <int>)asynchronousResult.AsyncState;
                    try
                    {
                        t.TrySetResult(_socket.EndSendTo(asynchronousResult));
                    }
                    catch (Exception)
                    {
                        t.TrySetResult(0);
                    }
                }, tcs);
            }
            catch (Exception)
            {
                return(false);
            }
            if (await Task.WhenAny(tcs.Task, Task.Delay(timeOutMilliseconds)) != tcs.Task)
            {
                return(false);
            }

            // The send operation was successful if as many bytes as are contained in the packet were actually sent.
            return(packet.Length == await tcs.Task);
        }
Esempio n. 9
0
        private void OnSendComplete(IAsyncResult asyncResult)
        {
            Socket s = (Socket)asyncResult.AsyncState;

            try {
                int bytes = s.EndSend(asyncResult);
                if (bytes <= 0)
                {
                    Dispose(false);
                    return;
                }
                _NextCheckActivity = Timing.Ticks + MsBeforeDisconnectNormal;
                SendQueue.Gram gram;
                lock (_SendQueue) {
                    gram = _SendQueue.Dequeue();
                    if (gram == null && _SendQueue.IsFlushReady)
                    {
                        gram = _SendQueue.CheckFlushReady();
                    }
                }
                if (gram != null)
                {
                    try {
                        s.BeginSendTo(gram.Buffer, 0, gram.Length, SocketFlags.None, _ClientEndPoint, _OnSendComplete, _Socket);
                    }
                    catch (Exception ex) {
                        TraceException(ex);
                        Dispose(false);
                    }
                }
                else
                {
                    lock (_SendLockMutex)
                        _sending = false;
                }
            }
            catch (Exception) {
                Dispose(false);
            }
        }
Esempio n. 10
0
        //connect and set up UDP to broadcast
        private void FormSim_Load(object sender, EventArgs e)
        {
            // Initialise delegate
            displayMessageDelegate = new DisplayMessageDelegate(DisplayMessage);

            try
            {
                ipAddress = tboxIP.Text.Trim();

                // Initialise socket
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

                // Initialise server IP
                IPAddress serverIP = IPAddress.Parse(ipAddress);

                // Initialise the IPEndPoint for the server and use port 30000
                epServer = new IPEndPoint(serverIP, (int)nudPort.Value);

                // Get packet as byte array
                byte[] data = Encoding.ASCII.GetBytes("Connecting");

                // Send data to server
                clientSocket.BeginSendTo(data, 0, data.Length, SocketFlags.None, epServer, new AsyncCallback(SendData), null);

                // Initialise data stream
                buffer = new byte[1024];

                timer1.Enabled = true;

                // Begin listening for broadcasts
                clientSocket.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);

                //start allowing nmea to be sent
                isConnected = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Connection Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 11
0
        void _timer_get2300Tag(object sender, EventArgs e)
        {
            __udpServer.Manualstate.WaitOne();
            __udpServer.Manualstate.Reset();
            string str = __udpServer.sbuilder.ToString();

            __udpServer.sbuilder.Remove(0, str.Length);
            if (this.__reader_info.sendType == ReaderInfo.sendTypeUDP)
            {
                byte[] byteData = Encoding.UTF8.GetBytes(str);
                foreach (EndPoint ep in this.endpoint_list)
                {
                    clientSocket.BeginSendTo(byteData, 0,
                                             byteData.Length, SocketFlags.None,
                                             ep, new AsyncCallback(OnSend), null);
                }
                string log = "接收到读写器数据";
                this.appendLog(log);
            }
            else
            {
                List <TagInfo> taglist = __2300helper.getTagList();
                foreach (TagInfo ti in taglist)
                {
                    string log = "检测到标签 " + ti.epc;
                    this.appendLog(log);

                    this.addTagsToServer(ti.epc);
                }
                __2300helper.ParseDataToTag(str);
                if (str != null && str.Length > 0)
                {
                    //Debug.WriteLine(
                    //    string.Format(".  _timer_get2300Tag -> string = {0}"
                    //    , str));
                }
            }

            __udpServer.Manualstate.Set();
        }
Esempio n. 12
0
        private void OnSend(IAsyncResult ar)
        {
            try
            {
                Socket.EndSend(ar);
            }
            catch (ObjectDisposedException)
            {
                return;
            }
            catch (SocketException ex)
            {
                // Fail
                if (ex.SocketErrorCode != SocketError.ConnectionRefused)
                {
                    Assert.Null(ex.Message);
                }
            }
            catch (Exception ex)
            {
                // Fail
                Assert.Null(ex.Message);
            }

            System.Threading.Thread.Sleep(WaitTime);

            try
            {
                Socket.BeginSendTo(RecvBuf, 0, RecvBuf.Length, SocketFlags.None, remoteEP, new AsyncCallback(OnSend), null);
            }
            catch (ObjectDisposedException)
            {
                return;
            }
            catch (Exception ex)
            {
                // Fail
                Assert.Null(ex.Message);
            }
        }
Esempio n. 13
0
 private void btnConectar_Click(object sender, EventArgs e)
 {
     try
     {
         //seteo en la variable el nombre ingresado
         nombre = txtNombre.Text.Trim();
         //se crean los paquetes iniciales
         Paquete paqueteInicio = new Paquete();
         paqueteInicio.NombreChat        = nombre;
         paqueteInicio.MensajeChat       = null;
         paqueteInicio.IdentificadorChat = IdentificadorDato.Conectado;
         //se instancia socket, con el constructor que acepta como parámetros de entrada el esquema de
         //direccionamiento, el tipo de socket, y el tipo de protocolo que en este caso es udp
         socketCliente = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         //se setea la dirección ip del servidor
         IPAddress servidorIP = IPAddress.Parse(txtServidor.Text.Trim());
         //se crea un punto remoto con la dirección ip del servidor y el puerto de escucha
         IPEndPoint puntoRemoto = new IPEndPoint(servidorIP, 30000);
         epServidor = (EndPoint)puntoRemoto;
         //se obtiene el arreglo de bytes de paquete inicial
         byte[] buferTx = paqueteInicio.ObtenerArregloBytes();
         //socket para envío de datos
         socketCliente.BeginSendTo(buferTx, 0, buferTx.Length, SocketFlags.None, epServidor, new
                                   //delegado al método ProcesarEnviar cuando se intenta la conexión
                                   AsyncCallback(ProcesarEnviar), null);
         //se setea el tamaño del buffer de recepción
         buferRx = new byte[1024];
         //se recibe asincrónicamente los datos
         socketCliente.BeginReceiveFrom(buferRx, 0, buferRx.Length, SocketFlags.None, ref epServidor, new
                                        //se hace referencia al método ProcesarRecibir cuando finalice la entrega asincrónica
                                        AsyncCallback(this.ProcesarRecibir), null);
     }
     catch (Exception ex)
     {
         //si se presenta un error se muestra por consola
         MessageBox.Show("Error al conectarse: " + ex.Message, "Cliente UDP",
                         MessageBoxButtons.OK,
                         MessageBoxIcon.Error);
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Sends the datagram with the asynchronous mode.
        /// </summary>
        /// <param name="sendBuffer">The send buffer.</param>
        /// <param name="sendBufferSize">Size of the send buffer.</param>
        public override void SendDatagram(byte[] sendBuffer, int sendBufferSize)
        {
            lock (mutex)
            {
                try
                {
                    int bufferOffset = 0;

                    // Sends data asynchronously to a socket.
                    if (socket != null)
                    {
                        socket.BeginSendTo(sendBuffer, bufferOffset, sendBufferSize, SocketFlags.None, this.remoteEndPoint, this.EndSendDatagram, this);
                    }
                }
                catch (System.Exception e)
                {
                    this.OnClientTeardown();
                    this.OnExceptionOccurred(e);
                    Utils.OutputMessage(false, MsgLevel.Error, "ClientSocketUdp -- SendDatagram", e.Message);
                }
            }
        }
Esempio n. 15
0
        public static void Broadcast(string data, int port)
        {
            Debug.WriteLine("Broadcast => " + data);

            Socket broadcastSocket = new Socket(AddressFamily.InterNetwork,
                                                SocketType.Dgram, ProtocolType.Udp);

            broadcastSocket.EnableBroadcast = true;
            IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, port);

            byte[] byteData = System.Text.Encoding.UTF8.GetBytes(data);
            try
            {
                broadcastSocket.BeginSendTo(byteData, 0,
                                            byteData.Length, SocketFlags.None,
                                            iep, null, null);
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine("Broadcast => " + ex.Message);
            }
        }
Esempio n. 16
0
        /*
         * Send a message to the remote party.
         */
        private void SendMessage(Command cmd, EndPoint sendToEP)
        {
            try
            {
                //Create the message to send.
                Data msgToSend = new Data();

                msgToSend.strName    = Nickname; //Name of the user.
                msgToSend.cmdCommand = cmd;      //Message to send.
                msgToSend.vocoder    = vocoder;  //Vocoder to be used.

                byte[] message = msgToSend.ToByte();

                //Send the message asynchronously.
                clientSocket.BeginSendTo(message, 0, message.Length, SocketFlags.None, sendToEP, new AsyncCallback(OnSend), null);
            }
            catch (Exception ex)
            {
                cGlobalVars.AddLogChat("VoiceChat-SendMessage > " + ex.Message);
                //MessageBox.Show(ex.Message, "VoiceChat-SendMessage ()", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 17
0
        public override Task <SocketError> SendAsync(SIPEndPoint dstEndPoint, byte[] buffer, string connectionIDHint)
        {
            if (dstEndPoint == null)
            {
                throw new ArgumentException("dstEndPoint", "An empty destination was specified to Send in SIPUDPChannel.");
            }
            else if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentException("buffer", "The buffer must be set and non empty for Send in SIPUDPChannel.");
            }

            try
            {
                IPEndPoint dstIPEndPoint = dstEndPoint.GetIPEndPoint();

                if (m_sendFailures.ContainsKey(dstEndPoint.GetIPEndPoint()))
                {
                    return(Task.FromResult(SocketError.ConnectionRefused));
                }
                else
                {
                    m_udpSocket.BeginSendTo(buffer, 0, buffer.Length, SocketFlags.None, dstIPEndPoint, EndSendTo, dstEndPoint);
                    return(Task.FromResult(SocketError.Success));
                }
            }
            catch (ObjectDisposedException) // Thrown when socket is closed. Can be safely ignored.
            {
                return(Task.FromResult(SocketError.Disconnecting));
            }
            catch (SocketException sockExcp)
            {
                return(Task.FromResult(sockExcp.SocketErrorCode));
            }
            catch (Exception excp)
            {
                logger.LogError($"Exception SIPUDPChannel.SendAsync. {excp}");
                return(Task.FromResult(SocketError.Fault));
            }
        }
        /// <summary>
        /// Reply to a search from a user via udp
        /// (active connection of peer user required)
        /// </summary>
        /// <param name="result_name">the filename of the share found</param>
        /// <param name="filesize">the filesize of the share</param>
        /// <param name="hub">the hub the user is connected to</param>
        /// <param name="search">a whole lot of parameters of the search initiated by a remote user (including ip and port,which we will need here)</param>
        public void SearchReply(string result_name, long filesize, Hub hub, Hub.SearchParameters search)
        {
            try
            {
                string temp_hub = hub.Name;
                if (search.HasTTH)
                {
                    temp_hub = "TTH:" + search.tth;
                }
                string reply = "$SR " + hub.Nick + " " + result_name + (char)0x05 + filesize + " 1/1" + (char)0x05 + temp_hub + " (" + hub.IP + ":" + hub.Port + ")|";
                Console.WriteLine("Replying to active search: " + reply);
                IPEndPoint udp_reply_endpoint = new IPEndPoint(IPAddress.Parse(search.ip), search.port);
                //EndPoint temp_receive_from_endpoint = (EndPoint)receive_from_endpoint;

                byte[] send_bytes = System.Text.Encoding.Default.GetBytes(reply);
                udp_socket.BeginSendTo(send_bytes, 0, send_bytes.Length, SocketFlags.None, udp_reply_endpoint, new AsyncCallback(SearchReplyCallback), udp_socket);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during sending of SearchReply to: " + search.ip + ":" + search.port + " : " + ex.Message);
            }
        }
Esempio n. 19
0
        /// <summary>Used internally by the netcode to send raw packets directly to the socket.</summary>
        /// <param name="remote">Remote address to send to.</param>
        /// <param name="buffer">Array to read from.</param>
        /// <param name="offset">Array offset to read from.</param>
        /// <param name="count">Number of bytes to read.</param>
        /// <returns>Task that returns number of bytes sent.</returns>
        internal async Task <int> SendSocketAsync(IPEndPoint remote, byte[] buffer, int offset, int count)
        {
            try {
                // Convert remote address if needed
                if (Socket.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    if (remote.AddressFamily != AddressFamily.InterNetworkV6)
                    {
                        remote = new IPEndPoint(remote.Address.MapToIPv6(), remote.Port);
                    }
                }
                else if (remote.Address.IsIPv4MappedToIPv6)
                {
                    remote = new IPEndPoint(remote.Address.MapToIPv4(), remote.Port);
                }

                // Send packet and wait for completion
                TaskCompletionSource <int> tcs = new TaskCompletionSource <int>();
                Socket.BeginSendTo(buffer, offset, count, SocketFlags.None, remote, result => {
                    try {
                        tcs.TrySetResult(Socket.EndSendTo(result));
                    } catch (Exception e) {
                        tcs.TrySetException(e);
                    }
                }, null);
                count = await tcs.Task;

                // Increment statistics
                Statistics.SetSocketSendTicks(Ticks);
                Statistics.IncrementSocketSendCount();
                Statistics.AddSocketSendBytes(count);

                // Return number of bytes sent
                return(count);
            } catch (Exception exception) {
                Listener.OnHostException(remote, exception);
                throw;
            }
        }
Esempio n. 20
0
        /// <summary>
        ///     Sends data from the listener socket.
        /// </summary>
        /// <param name="bytes">The bytes to send.</param>
        /// <param name="endPoint">The endpoint to send to.</param>
        internal void SendData(byte[] bytes, int length, EndPoint endPoint)
        {
            if (length > bytes.Length)
            {
                return;
            }

#if DEBUG
            if (TestDropRate > 0)
            {
                if (Interlocked.Increment(ref dropCounter) % TestDropRate == 0)
                {
                    return;
                }
            }
#endif

            try
            {
                socket.BeginSendTo(
                    bytes,
                    0,
                    length,
                    SocketFlags.None,
                    endPoint,
                    SendCallback,
                    null
                    );
            }
            catch (SocketException e)
            {
                throw new HazelException("Could not send data as a SocketException occurred.", e);
            }
            catch (ObjectDisposedException)
            {
                //Keep alive timer probably ran, ignore
                return;
            }
        }
Esempio n. 21
0
        //sends byte array
        public void SendUDPMessage(byte[] byteData)
        {
            if (isUDPSendConnected)
            {
                try
                {
                    IPEndPoint EndPt = new IPEndPoint(epIP, SendToPort);

                    // Send packet to the zero
                    if (byteData.Length != 0)
                    {
                        sendSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, EndPt, new AsyncCallback(SendData), null);
                    }
                    //mf.WriteEvent("sent udp message to control box " + byteData[2].ToString());
                }
                catch (Exception e)
                {
                    mf.Tls.WriteErrorLog("Sending UDP Message" + e.ToString());
                    mf.Tls.TimedMessageBox("Send Error", e.Message);
                }
            }
        }
Esempio n. 22
0
        private async void Run()
        {
            Socket   s        = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            EndPoint endPoint = new IPEndPoint(IPAddress.Loopback, 10_000);

            while (true)
            {
                Image        image        = new Bitmap(await GetScreen());
                MemoryStream memoryStream = new MemoryStream();
                image.Save(memoryStream, ImageFormat.Jpeg);
                byte[] send = memoryStream.ToArray();
                int    len  = 0;

                int sended = 0;
                while (sended != send.Length)
                {
                    if (sended < send.Length - 500)
                    {
                        len = await Task.Factory.FromAsync(s.BeginSendTo(send, sended, 500, SocketFlags.None, endPoint, null, null),
                                                           s.EndSendTo);

                        sended += 500;
                    }
                    else
                    {
                        len = await s.SendTo(send, 500, send.Length - sended, SocketFlags.None, endPoint);

                        sended += send.Length - sended;
                    }
                }
                await s.SendTo(send, 0, 0, SocketFlags.None, endPoint);

                //Thread.Sleep(interval);
                await Task.Delay(interval);

                memoryStream.Close();
            }
        }
Esempio n. 23
0
 /// <summary>
 /// This method is the process used by the methods SendTo.
 /// This method can send a message to a given machine. The IPEndPoint corresponding to the machine
 /// is specified by the (<paramref name="target"/>) parameter.
 /// The message is specified in the (<paramref name="text"/>) parameter.
 /// <example>For example:
 /// <code>
 ///    UdpSocket socket = new UdpSocket();
 ///    socket.Start("127.0.0.1", 27000);
 ///    socket.SendTo("127.0.0.1", 27000, "Hello");
 /// </code>
 /// This code creat a new udpSocket and use it to send the message "Hello" to itself.
 /// </example>
 /// </summary>
 ///<param name="target">The IPEndPoint used to bind the socket on</param>
 ///<param name="text">The message to send as a string </param>
 private void SendToProcess(IPEndPoint target, string text)
 {
     if (!IsActive)
     {
         return;
     }
     try
     {
         var data      = Encoding.ASCII.GetBytes(text);
         var sendState = new State(_bufSize);
         _socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, target, (ar) =>
         {
             var so = (State)ar.AsyncState;
             try
             {
                 var bytes = _socket.EndSend(ar);
                 if (_verbose)
                 {
                     Console.WriteLine("SEND: {0}, {1}", bytes, text);
                 }
             }
             catch
             {
                 if (_verbose)
                 {
                     Console.WriteLine("Unable to send message to: {0}", target);
                 }
             }
         }, sendState);
     }
     catch
     {
         if (_verbose)
         {
             Console.WriteLine("Destination unavailable");
         }
     }
 }
Esempio n. 24
0
        private void btnLogin_Click(object sender, EventArgs e)
        {
            strName = txtName.Text;
            try
            {
                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Dgram, ProtocolType.Udp);

                //IP address of the server machine
                IPAddress ipAddress = IPAddress.Parse(txtServerIP.Text);
                //Server is listening on port 1000
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);

                epServer = (EndPoint)ipEndPoint;

                Data msgToSend = new Data();
                msgToSend.cmdCommand = Command.Login;
                msgToSend.strName    = strName;
                msgToSend.strMessage = null;

                byte[] byteData = msgToSend.ToByte();

                //Login to the server
                clientSocket.BeginSendTo(byteData, 0, byteData.Length,          //處理多個資訊
                                         SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient",
                                MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            ClientChat_from clientChat_From = new ClientChat_from();

            clientChat_From.Show();
            this.Hide();    //藏起來
        }
Esempio n. 25
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            strName = txtName.Text;
            try
            {
                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork,
                                          SocketType.Dgram, ProtocolType.Udp);

                //IP address of the server machine
                if (txtServerIP.Text == "Domo")
                {
                    string    serverIp  = "127.0.0.1";
                    IPAddress ipAddress = IPAddress.Parse(serverIp);

                    //Server is listening on port 1000
                    IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 1000);
                    epServer = (EndPoint)ipEndPoint;
                    Data msgToSend = new Data();
                    msgToSend.cmdCommand = Command.Login;
                    msgToSend.strMessage = null;
                    msgToSend.strName    = strName;
                    byte[] byteData = msgToSend.ToByte();

                    //Login to the server
                    clientSocket.BeginSendTo(byteData, 0, byteData.Length,
                                             SocketFlags.None, epServer, new AsyncCallback(OnSend), null);
                }
                else
                {
                    MessageBox.Show("Wrong group name!!!!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 26
0
 public void SendBytes(IPEndPoint endPoint, byte[] data)
 {
     PacketSending(endPoint, data, data.Length);
     try
     {
         _socket.BeginSendTo(data, 0, data.Length, SocketFlags.None, endPoint, (ar) =>
         {
             try
             {
                 StateObject so = (StateObject)ar.AsyncState;
                 int bytes      = _socket.EndSend(ar);
             }
             catch (Exception ex)
             {
                 OnSocketError?.Invoke(endPoint, ex);
             }
         }, state);
     }
     catch (Exception ex)
     {
         OnSocketError?.Invoke(endPoint, ex);
     }
 }
Esempio n. 27
0
    private static void Send(Socket handler, List <ReturnRecentItems> items, StateObject state)
    {
        IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.7"), 11000);

        // Convert the string data to byte data using ASCII encoding.
        foreach (var data in items)
        {
            byte[] byteData = Encoding.ASCII.GetBytes(data.ValueOfItem.ToString());

            handler.BeginSendTo(byteData,
                                0,
                                byteData.Length,
                                0,
                                localEndPoint,
                                SendCallback,
                                state);

            //handler.BeginSend(byteData, 0, byteData.Length, 0,
            //new AsyncCallback(SendCallback), handler);
        }

        // Begin sending the data to the remote device.
    }
Esempio n. 28
0
 private void btnIngresar_Click(object sender, EventArgs e)
 {
     try
     {
         nombre = txtNombre.Text.Trim();
         Paquete paqueteInicio = new Paquete();
         paqueteInicio.NombreChat        = nombre;
         paqueteInicio.MensajeChat       = null;
         paqueteInicio.IdentificadorChat = Paquete.IdentificadorDato.Conectado;
         socketCliente = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
         IPAddress  servidorIP  = IPAddress.Parse(txtServidor.Text.Trim());
         IPEndPoint puntoRemoto = new IPEndPoint(servidorIP, 30000);
         epServidor = (EndPoint)puntoRemoto;
         byte[] buferTx = paqueteInicio.ObtenerArregloBytes();
         socketCliente.BeginSendTo(buferTx, 0, buferTx.Length, SocketFlags.None, epServidor, new AsyncCallback(ProcesarEnviar), null);
         buferRx = new byte[1024];
         socketCliente.BeginReceiveFrom(buferRx, 0, buferRx.Length, SocketFlags.None, ref epServidor, new AsyncCallback(this.ProcesarRecibir), null);
     }
     catch (Exception ex)
     {
         MessageBox.Show("Error al conectarse: " + ex.Message, "Cliente UDP", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
Esempio n. 29
0
        private void SendUDPMessage(string message)
        {
            if (isSendConnected)
            {
                try
                {
                    // Get packet as byte array
                    byte[] byteData = Encoding.ASCII.GetBytes(message);

                    if (byteData.Length != 0)
                    {
                        // Send packet to the zero
                        sendSocket.BeginSendTo(byteData, 0, byteData.Length, SocketFlags.None, epAutoSteer, new AsyncCallback(SendData), null);
                    }
                }
                catch (Exception e)
                {
                    WriteErrorLog("Sending UDP Message" + e.ToString());

                    MessageBox.Show("Send Error: " + e.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 /// <inheritdoc />
 protected override void WriteBytesToConnection(byte[] bytes)
 {
     try
     {
         socket.BeginSendTo(
             bytes,
             0,
             bytes.Length,
             SocketFlags.None,
             RemoteEndPoint,
             HandleSendTo,
             null);
     }
     catch (NullReferenceException) { }
     catch (ObjectDisposedException)
     {
         // Already disposed and disconnected...
     }
     catch (SocketException ex)
     {
         DisconnectInternal(HazelInternalErrors.SocketExceptionSend, "Could not send data as a SocketException occurred: " + ex.Message);
     }
 }
Esempio n. 31
0
        private void DualModeBeginSendTo_EndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer, bool expectedToTimeout = false)
        {
            int port;
            Socket client = new Socket(SocketType.Dgram, ProtocolType.Udp);
            using (SocketUdpServer server = new SocketUdpServer(_log, listenOn, dualModeServer, out port))
            {
                // Send a few packets, in case they aren't delivered reliably.
                for (int i = 0; i < Configuration.UDPRedundancy; i++)
                {
                    IAsyncResult async = client.BeginSendTo(new byte[1], 0, 1, SocketFlags.None, new IPEndPoint(connectTo, port), null, null);

                    int sent = client.EndSendTo(async);
                    Assert.Equal(1, sent);
                }

                bool success = server.WaitHandle.WaitOne(expectedToTimeout ? Configuration.FailingTestTimeout : Configuration.PassingTestTimeout); // Make sure the bytes were received
                if (!success)
                {
                    throw new TimeoutException();
                }
            }
        }
Esempio n. 32
0
        [Fact] // Base case
        // "The parameter remoteEP must not be of type DnsEndPoint."
        public void Socket_BeginSendToDnsEndPoint_Throws()
        {
            Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            Assert.Throws<ArgumentException>(() =>
            {
                socket.BeginSendTo(new byte[1], 0, 1, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null);
            });
        }
Esempio n. 33
0
        [Fact] // Base case
        // "The system detected an invalid pointer address in attempting to use a pointer argument in a call"
        public void Socket_BeginSendToV4IPEndPointToV4Host_Throws()
        {
            Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);
            socket.DualMode = false;

            Assert.Throws<SocketException>(() =>
            {
                socket.BeginSendTo(new byte[1], 0, 1, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, UnusedPort), null, null);
            });
        }
Esempio n. 34
0
 public void Send(string ip, int port, byte[] temp_sendbuffer)
 {
     socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     socket.BeginSendTo(temp_sendbuffer, 0, temp_sendbuffer.Length, SocketFlags.None, (EndPoint)(new IPEndPoint(IPAddress.Parse(ip), port)), new AsyncCallback(SendTo_Callback), socket);
 }
Esempio n. 35
0
 public void Socket_BeginSendToDnsEndPoint_ArgumentException()
 {
     using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
     {
         Assert.Throws<ArgumentException>(() =>
         {
             sock.BeginSendTo(new byte[10], 0, 0, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null);
         });
     }
 }
Esempio n. 36
0
        private void DualModeBeginSendTo_EndPointToHost_Helper(IPAddress connectTo, IPAddress listenOn, bool dualModeServer)
        {
            int port;
            Socket client = new Socket(SocketType.Dgram, ProtocolType.Udp);
            using (SocketUdpServer server = new SocketUdpServer(listenOn, dualModeServer, out port))
            {
                IAsyncResult async = client.BeginSendTo(new byte[1], 0, 1, SocketFlags.None, new IPEndPoint(connectTo, port), null, null);

                int sent = client.EndSendTo(async);
                Assert.Equal(1, sent);

                bool success = server.WaitHandle.WaitOne(100); // Make sure the bytes were received
                if (!success)
                {
                    throw new TimeoutException();
                }
            }
        }