无线节目延迟 [英] delay in wireless program

查看:63
本文介绍了无线节目延迟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

hi
我正在编写使用的无线程序,
我从本网站下载的操纵杆类
,但使用操纵杆发送命令时会有延迟,

hi
im writing the wireless program that using ,
joy stick class that i downloaded from this site
, but there is delay when i send command , with joy stick,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.DirectX.DirectInput;
using System.Diagnostics;

namespace new_joystick
{
        public class Joystick
        {
            private Device joystickDevice;
            private JoystickState state;

            private int axisCount;
            /// <summary>
            /// Number of axes on the joystick.
            /// </summary>
            public int AxisCount
            {
                get { return axisCount; }
            }

            private int axisA;
            /// <summary>
            /// The first axis on the joystick.
            /// </summary>
            public int AxisA
            {
                get { return axisA; }
            }

            private int axisB;
            /// <summary>
            /// The second axis on the joystick.
            /// </summary>
            public int AxisB
            {
                get { return axisB; }
            }

            private int axisC;
            /// <summary>
            /// The third axis on the joystick.
            /// </summary>
            public int AxisC
            {
                get { return axisC; }
            }

            private int axisD;
            /// <summary>
            /// The fourth axis on the joystick.
            /// </summary>
            public int AxisD
            {
                get { return axisD; }
            }

            private int axisE;
            /// <summary>
            /// The fifth axis on the joystick.
            /// </summary>
            public int AxisE
            {
                get { return axisE; }
            }

            private int axisF;
            /// <summary>
            /// The sixth axis on the joystick.
            /// </summary>
            public int AxisF
            {
                get { return axisF; }
            }
            private IntPtr hWnd;

            private bool[] buttons;
            /// <summary>
            /// Array of buttons availiable on the joystick. This also includes PoV hats.
            /// </summary>
            public bool[] Buttons
            {
                get { return buttons; }
            }

            private string[] systemJoysticks;

            /// <summary>
            /// Constructor for the class.
            /// </summary>
            /// <param name="window_handle">Handle of the window which the joystick will be "attached" to.</param>
            public Joystick(IntPtr window_handle)
            {
                hWnd = window_handle;
                axisA = -1;
                axisB = -1;
                axisC = -1;
                axisD = -1;
                axisE = -1;
                axisF = -1;
                axisCount = 0;
            }

            private void Poll()
            {
                try
                {
                    // poll the joystick
                    joystickDevice.Poll();
                    // update the joystick state field
                    state = joystickDevice.CurrentJoystickState;
                }
                catch (Exception err)
                {
                    // we probably lost connection to the joystick
                    // was it unplugged or locked by another application?
                    Debug.WriteLine("Poll()");
                    Debug.WriteLine(err.Message);
                    Debug.WriteLine(err.StackTrace);
                }
            }

            /// <summary>
            /// Retrieves a list of joysticks attached to the computer.
            /// </summary>
            /// <example>
            /// [C#]
            /// <code>
            /// JoystickInterface.Joystick jst = new JoystickInterface.Joystick(this.Handle);
            /// string[] sticks = jst.FindJoysticks();
            /// </code>
            /// </example>
            /// <returns>A list of joysticks as an array of strings.</returns>
            public string[] FindJoysticks()
            {
                systemJoysticks = null;

                try
                {
                    // Find all the GameControl devices that are attached.
                    DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);

                    // check that we have at least one device.
                    if (gameControllerList.Count > 0)
                    {
                        systemJoysticks = new string[gameControllerList.Count];
                        int i = 0;
                        // loop through the devices.
                        foreach (DeviceInstance deviceInstance in gameControllerList)
                        {
                            // create a device from this controller so we can retrieve info.
                            joystickDevice = new Device(deviceInstance.InstanceGuid);
                            joystickDevice.SetCooperativeLevel(hWnd,
                                CooperativeLevelFlags.Background |
                                CooperativeLevelFlags.NonExclusive);

                            systemJoysticks[i] = joystickDevice.DeviceInformation.InstanceName;

                            i++;
                        }
                    }
                }
                catch (Exception err)
                {
                    Debug.WriteLine("FindJoysticks()");
                    Debug.WriteLine(err.Message);
                    Debug.WriteLine(err.StackTrace);
                }

                return systemJoysticks;
            }

            /// <summary>
            /// Acquire the named joystick. You can find this joystick through the <see cref="FindJoysticks"/> method.
            /// </summary>
            /// <param name="name">Name of the joystick.</param>
            /// <returns>The success of the connection.</returns>
            public bool AcquireJoystick(string name)
            {
                try
                {
                    DeviceList gameControllerList = Manager.GetDevices(DeviceClass.GameControl, EnumDevicesFlags.AttachedOnly);
                    int i = 0;
                    bool found = false;
                    // loop through the devices.
                    foreach (DeviceInstance deviceInstance in gameControllerList)
                    {
                        if (deviceInstance.InstanceName == name)
                        {
                            found = true;
                            // create a device from this controller so we can retrieve info.
                            joystickDevice = new Device(deviceInstance.InstanceGuid);
                            joystickDevice.SetCooperativeLevel(hWnd,
                                CooperativeLevelFlags.Background |
                                CooperativeLevelFlags.NonExclusive);
                            break;
                        }

                        i++;
                    }

                    if (!found)
                        return false;

                    // Tell DirectX that this is a Joystick.
                    joystickDevice.SetDataFormat(DeviceDataFormat.Joystick);

                    // Finally, acquire the device.
                    joystickDevice.Acquire();

                    // How many axes?
                    // Find the capabilities of the joystick
                    DeviceCaps cps = joystickDevice.Caps;
                    Debug.WriteLine("Joystick Axis: " + cps.NumberAxes);
                    Debug.WriteLine("Joystick Buttons: " + cps.NumberButtons);

                    axisCount = cps.NumberAxes;

                    UpdateStatus();
                }
                catch (Exception err)
                {
                    Debug.WriteLine("FindJoysticks()");
                    Debug.WriteLine(err.Message);
                    Debug.WriteLine(err.StackTrace);
                    return false;
                }

                return true;
            }

            /// <summary>
            /// Unaquire a joystick releasing it back to the system.
            /// </summary>
            public void ReleaseJoystick()
            {
                joystickDevice.Unacquire();
            }

            /// <summary>
            /// Update the properties of button and axis positions.
            /// </summary>
            public void UpdateStatus()
            {
                Poll();

                int[] extraAxis = state.GetSlider();
                //Rz Rx X Y Axis1 Axis2
                axisA = state.Rz;
                axisB = state.Rx;
                axisC = state.X;
                axisD = state.Y;
                axisE = extraAxis[0];
                axisF = extraAxis[1];
 }


我认为有些部分会延迟


i think there is section that make a delay

// not using buttons, so don't take the tiny amount of time it takes to get/parse  please
                byte[] jsButtons = state.GetButtons();
                buttons = new bool[jsButtons.Length];

                int i = 0;
                foreach (byte button in jsButtons)
                {
                    buttons[i] = button &gt;= 20;
                    i++;
                }
            }
        }


我认为按钮(按钮而不是轴)的延迟取决于最后一块.
及其连接和发送数据的部分


i think that the delay of the button (button not axis) it`s depend on this last block.
and it ` s section that connect and send data

void senddata(string messagebody)
        {
            try
            {
                byte[] data = new byte[100];
                data = Encoding.ASCII.GetBytes(messagebody);
                client.Send(data, data.Length, SocketFlags.None);
            }
            catch(Exception F)
            {
                label2.Text = F.Message;
            }
        }
        Socket client;
        Socket newsock;
        private void button3_Click(object sender, EventArgs e)
        {
            byte[] data = new byte[100];
            IPAddress ip = IPAddress.Parse("192.168.0.100");
            IPEndPoint ipep = new IPEndPoint(ip, 8001);
            newsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            newsock.Bind(ipep);
            newsock.Listen(1);
            client = newsock.Accept();
            IPEndPoint newclinet = (IPEndPoint)client.RemoteEndPoint;
            label2.Text = "Connected with  " + newclinet.Address + "   at port  " + newclinet.Port;
            string welcome = "Welcome goh to U.S.R.F wireless program";
            data = Encoding.ASCII.GetBytes(welcome);
            client.Send(data, data.Length, SocketFlags.None);
            timer1.Enabled = true;
        }
        private void timer1_Tick(object sender, EventArgs e)
        {
            byte[] data = new byte[1024];
            int recv;
            data = new byte[1024];
            recv = client.Receive(data);
            if (recv != 0)
            {
                label3.Text = " ";
                label3.Text += Encoding.ASCII.GetString(data, 0, recv);
            }
        }
        private void button4_Click(object sender, EventArgs e)
        {
            senddata(textBox1.Text); 
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            client.Shutdown(SocketShutdown.Both);
            client.Close();
        }

我在服务器程序中使用两个计时器发送和接收数据,在客户端中使用一个线程和一个计时器发送和接收数据,有人可以告诉我为什么我的程序有延迟吗?

i use two timer for send and recieve data in server program and one thread and one timer for send and recieve in client ,,, can anyone tell me why my program has delay ???

推荐答案

首先,您提供了太多的代码.我们不会为您调试程序.由您自己确定发生了什么,什么地方不起作用.

其次,几乎不可能告诉您在哪里看到延迟".

我建议使用DateTime类和Now()方法来确定花费很长时间的内容,然后使用花费很长时间的代码返回给我们.

为此,请创建一个名为StartTime之类的新变量,并将其设置为 DateTime.Now().例如:
First of all, you provided way too much code. We''re not going to debug your program for you. It''s up to you to figure out what''s going on and where things aren''t working.

Secondly, it''s nearly impossible to tell where you''re seeing a "delay".

I would suggest using the DateTime class and the Now() method to determine what is taking so long, and then come back to us with the code that it taking a long time.

To do that, create a new variable called something like StartTime and set it to DateTime.Now(). For instance something like:
private void Poll()
{
      DateTime startTime = DateTime.Now;

      try
      {
           // poll the joystick
           joystickDevice.Poll();

           Debug.Print("joystickDevice.Poll(): " + 
                       DateTime.Now.Subtract(startTime).TotalMilliseconds.ToString() +
                       " ms")

           // update the joystick state field
           state = joystickDevice.CurrentJoystickState;
      }
      catch (Exception err)
      {
           // we probably lost connection to the joystick
           // was it unplugged or locked by another application?
           Debug.WriteLine("Poll()");
           Debug.WriteLine(err.Message);
           Debug.WriteLine(err.StackTrace);
      }
}



在您认为可能会降低速度的地方尝试一下,您将能够看到什么在延迟"您的程序.



Try that in places you think could be slowing it down and you will be able to see what is "delaying" your program.


您好,

添加一种方法:
Hi,

add one method:
public static void log(string s) {
    if (s.Length!=0) s=DateTime.Now.ToString("HH:mm:ss.fff  ")+s;
    Console.WriteLine(s);
    // optionally uncomment:
    // File.AppendAllText("logfile.txt", s+Environment.NewLine);
}



然后通过调用替换所有调试打印.这样,您的所有输出都将加上时间戳,并且延迟应该很明显.

:)



then replace all debug printing by calls to it. That way all your output will be timestamped and the delays should be obvious.

:)


有很多原因可能会导致延迟".如果实际注册一个按钮似乎花费太长时间,那么您可能想查看调用UpdateStatus的位置,应该经常调用它,因为如果没有它,您将无法获得有关哪个键的任何信息.自上次通话以来已被按下.

其次,如果您正在通过网络发送输入,那么将会有很小的延迟(5-100毫秒),并且如果您使用计时器来发送和接收数据,则延迟可能只是时间在计时器的刻度之间.很难理解,使用其他人提供的信息来确定延迟在哪里,然后您将有很大的机会解决延迟.
There are numerous reasons why there could be ''delay''. If it seems to be taking too long to actually register that you''ve pressed a button then you may want to look into where you call UpdateStatus, it should be called frequently because without it you will not get any information on which keys have been pressed since the last call.

Secondly, if you''re sending the input over a network then there are going to be small delays (5 - 100''s of milliseconds) and if you are using timers to send and receive data then the delay could simply be the time between Ticks of the timer. It is difficult for use to know, use the information others have given to determine where the delay is and then you will stand a good chance of fixing it.


这篇关于无线节目延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆