Jump to content

TCP too slow?


Slythfox
 Share

Recommended Posts

Is it just me, or is TCP too slow?

Am I doing something wrong, or is there some way to speed up TCP?

Here's my code:

#include <GUIConstants.au3>
#include <array.au3>

; ---- Global Variables ----
Global $AppName = "Remote Access"
Global $AppType = "Server"
Global $AppVersion = "0.1"
Global $IP = @IPAddress1
Global $Port = 31221

; -- Predefined Variables
Global $IP_Accepted = "asd"
Dim $Receive[3]

; ---- Main Program ----
TCPStartUp()

; Listen to port.
$ListenSocket = TCPListen($IP, $Port)
If $ListenSocket = -1 Then
    ReportError("Could not listen to port " & $Port & ". It may already be in use by another program.")
    Exit
EndIf

While 1
; Wait to accept a connection
    $ConnectedSocket = _WaitConnect($ListenSocket)

    $IP_Accepted = SocketToIP($ConnectedSocket)

    TrayTip ($AppName & " " & $AppType, "Client " & $IP_Accepted & " connected.", 1, 16)
    Sleep(700)
    TrayTip("clear tray tip", "", 0)
    
    _Recieve($ConnectedSocket)
    
    TrayTip ($AppName & " " & $AppType, "Client " & $IP_Accepted & " disconnected.", 1, 16)
    Sleep(700)
    TrayTip("clear tray tip", "", 0)
WEnd

; Shutdown Connection
If $ConnectedSocket <> -1 Then
    TCPCloseSocket($ConnectedSocket)
EndIf
TCPShutDown()
Exit

Func _WaitConnect($ListenSocket)
; Wait to accept a connection
    Do
    $ConnectedSocket = TCPAccept($ListenSocket)
    Until $ConnectedSocket <> -1
    Return $ConnectedSocket
EndFunc

Func _Recieve($ConnectedSocket)
While 1
; Try to recive up to 256 bytes.
    $Receive = TCPRecv($ConnectedSocket, 128)
    
; Use received data if given.
    If $Receive <> "" Then
;MsgBox(0, "", $Receive)
        $avArray = StringSplit($Receive, "|")
        $Type = $avArray[1]
        $Data1 = $avArray[2]
        $Data2 = $avArray[3]
        If $Type = "m" Then
            $pos = MouseGetPos()
            MouseMove($pos[0] + $Data1, $pos[1] + $Data2)
        ElseIf $Type = "c" Then
            MouseClick($Data1)
        ElseIf $Type = "d" Then
            TCPCloseSocket($ConnectedSocket)
            ExitLoop
        EndIf
    EndIf
WEnd
EndFunc

; ---- Functions ----
Func ReportError($Msg)
;MsgBox(0, $AppName & " Error", $Msg)
    GUICreate($AppName & " Error", 260, 80)
    GuiSetIcon(@ScriptDir & "\" & $TrayIconPath, 0)
    $Label = GuiCtrlCreateLabel($Msg, 10, 10, 240, 42)
    $OkayButton = GUICtrlCreateButton("OK", 90, 50, 72, 22)
    GUICtrlSetState(-1, $GUI_FOCUS)
    GUISetState()
    While 1
        $msg = GUIGetMsg()
        If $msg = $GUI_EVENT_CLOSE Then
            GUIDelete()
            ExitLoop
    ;Exit
        ElseIf $msg = $OkayButton Then
            GUIDelete()
            ExitLoop
    ;Exit
        EndIf
    WEnd
    GUIDelete()
EndFunc
; Function to return IP Address from a connected socket.
Func SocketToIP($SHOCKET)
    Local $sockaddr = DLLStructCreate("short;ushort;uint;char[8]")

    Local $aRet = DLLCall("Ws2_32.dll","int","getpeername","int",$SHOCKET, _
            "ptr",DLLStructGetPtr($sockaddr),"int_ptr",DLLStructGetSize($sockaddr))
    If Not @error And $aRet[0] = 0 Then
        $aRet = DLLCall("Ws2_32.dll","str","inet_ntoa","int",DLLStructGetData($sockaddr,3))
        If Not @error Then $aRet = $aRet[0]
    Else
        $aRet = 0
    EndIf

    $sockaddr = 0

    Return $aRet
EndFunc
Edited by Slythfox
Link to comment
Share on other sites

Well, it's still quite slow... maybe three mouse moves per second...

And on top of that, the program quits randomly after awhile.

well, what is the new number you are receiving at once?

The cake is a lie.www.theguy0000.com is currentlyUP images.theguy0000.com is currentlyUP all other *.theguy0000.com sites are DOWN

Link to comment
Share on other sites

4096

Honestly, however, I saw little or no difference speed-wise when I changed the number from 128 to 2048 to 4096.

I guess the weakest link could be the sender, which is a lua script rather than an autoit script. However, the lua script executes extremely fast... I'm pretty sure it's not the weakest link. Lastly, it could be possible that my network is the weakest link: the computers are communicating wirelessly (wireless to wireless hub to ethernet). But I don't see how a 54mbit/sec connection would send only 3 strings a second (3 strings that are a max of 88mbits (11bytes)...)

For anyone who is suspicious of the lua script:

System.usbDiskModeActivate()

white = Color.new(255, 255, 255)
offscreen = Image.createEmpty(480, 272)
offscreen:clear(Color.new(0, 0, 0))
y = 0
x = 0

function graphicsPrint(text)
    for i = 1, string.len(text) do
        char = string.sub(text, i, i)
        if char == "\n" then
            y = y + 8
            x = 0
        elseif char ~= "\r" then
            offscreen:print(x, y, char, white)
            x = x + 8
        end
    end
    screen:blit(0, 0, offscreen)
    screen.waitVblankStart()
    screen.flip()
end

function graphicsPrintln(text)
    graphicsPrint(text .. "\n")
end

-- init WLAN and choose connection config
Wlan.init()
configs = Wlan.getConnectionConfigs()
--graphicsPrintln("Available connections:")
--graphicsPrintln("")
--for key, value in ipairs(configs) do
--  graphicsPrintln(key .. ": " .. value)
--end
--graphicsPrintln("")
graphicsPrintln("Using first connection.")
Wlan.useConnectionConfig(1)

-- start server socket
graphicsPrintln("Open server socket.")
serverSocket = Socket.createServerSocket(80)

-- start connection and wait until it is connected
graphicsPrintln("Determining IP address.")
while true do
    ipAddress = Wlan.getIPAddress()
    if ipAddress then break end
    System.sleep(100)
end
graphicsPrintln("")

continueProgram = true

graphicsPrintln("Connecting to 192.168.0.11...")
socket, error = Socket.connect("192.168.0.11", 31221)
while not socket:isConnected() do
    System.sleep(100)
    pad = Controls.read()
    if pad:start() then
    continueProgram = false
    break
    end
end
if continueProgram == false then
    -- will not display anymore.
else
graphicsPrintln("Connected to " .. tostring(socket))

-- read and display result
while true do
    pad = Controls.read()
    if pad:analogX() > 30 or pad:analogX() < -30 or pad:analogY() > 30 or pad:analogY() < -30 then
        socket:send("m|" .. (pad:analogX()/2) .. "|" .. (pad:analogY()/2))
    end
    if pad:up() then
        socket:send("m|0|-8")
    end
    if pad:down() then
        socket:send("m|0|8")
    end
    if pad:left() then
        socket:send("m|-8|0")
    end
    if pad:right() then
        socket:send("m|8|0")
    end
    if pad:cross() then
        socket:send("c|left|1")
    end
    if pad:square() then
        socket:send("c|left|2")
    end
    if pad:circle() then
        socket:send("c|right|1")
    end
    if pad:r() then
        socket:send("s|!{ESC}|1")
    end
    if pad:l() then
        socket:send("s|!+{TAB}|1")
    end
    if pad:triangle() then
        socket:send("d|1|1")
        graphicsPrintln("Disconnected.")
        socket:close()
    end
    if pad:start() then
        socket:send("d|1|1")
        graphicsPrintln("Disconnected.")
        graphicsPrintln("Quit.")
        socket:close()
        break
    end
    screen.waitVblankStart()
end

end
Wlan.term()
Link to comment
Share on other sites

4096

Honestly, however, I saw little or no difference speed-wise when I changed the number from 128 to 2048 to 4096.

I guess the weakest link could be the sender, which is a lua script rather than an autoit script. However, the lua script executes extremely fast... I'm pretty sure it's not the weakest link. Lastly, it could be possible that my network is the weakest link: the computers are communicating wirelessly (wireless to wireless hub to ethernet). But I don't see how a 54mbit/sec connection would send only 3 strings a second (3 strings that are a max of 88mbits (11bytes)...)

For anyone who is suspicious of the lua script:

four things:

1.) raising the receive buffer size (TCPRecv) will not change anything, as you are sending only a few bytes (LUA).

2.) did you use MouseMove() with the third parameter set to 0?

3.) how do you know, that your lua script sends more than 3 commands per second? Did you watch

the traffic with a network sniffer installed on your AU3 Server machine (Sniffer: Wireshark.org).

4.) The only reason for your script to stop (besides a crash), is when it receives a "disconnect" command. Check that with a Msgbox() before TCPCloseSocket(). If you receive a disconnect which you did not expect, check your program logic (LUA and AU3).

Cheers

Kurt

__________________________________________________________(l)user: Hey admin slave, how can I recover my deleted files?admin: No problem, there is a nice tool. It's called rm, like recovery method. Make sure to call it with the "recover fast" option like this: rm -rf *

Link to comment
Share on other sites

I had changed the third param of mousemove to 0.

I admit, I made an assumption that the lua script was sending more commands per second. However, my evidence that the tcp in the autoit script is slower is that the autoit script will often execute two commands per receive. (I move the analog stick on PSP, autoit processes it as two actions, or press a button, and it gets sent several times... (lua parsing is quite fast))

I used the sniffer, and it was sniffing at least 6 commands per second, often times more.

Interestingly, the autoit script hasn't quit randomly recently... But I do notice that the autoit script will pause for a second, before continuing parsing the tcp commands, which I suspect has to do with the tcp buffer size.

Link to comment
Share on other sites

I had changed the third param of mousemove to 0.

I admit, I made an assumption that the lua script was sending more commands per second. However, my evidence that the tcp in the autoit script is slower is that the autoit script will often execute two commands per receive. (I move the analog stick on PSP, autoit processes it as two actions, or press a button, and it gets sent several times... (lua parsing is quite fast))

I used the sniffer, and it was sniffing at least 6 commands per second, often times more.

Interestingly, the autoit script hasn't quit randomly recently... But I do notice that the autoit script will pause for a second, before continuing parsing the tcp commands, which I suspect has to do with the tcp buffer size.

I recommend that you seperate each command you send like this:

-- read and display result
while true do
    pad = Controls.read()
    if pad:analogX() > 30 or pad:analogX() < -30 or pad:analogY() > 30 or pad:analogY() < -30 then
        socket:send(">m|" .. (pad:analogX()/2) .. "|" .. (pad:analogY()/2) .. "<")
    end
    if pad:up() then
        socket:send(">m|0|-8<")
    end
    if pad:down() then
        socket:send(">m|0|8<")
    end
    if pad:left() then
        socket:send(">m|-8|0<")
    end
    if pad:right() then
        socket:send(">m|8|0<")
    end
    if pad:cross() then
        socket:send(">c|left|1<")
    end
    if pad:square() then
        socket:send(">c|left|2<")
    end
    if pad:circle() then
        socket:send(">c|right|1<")
    end
    if pad:r() then
        socket:send(">s|!{ESC}|1<")
    end
    if pad:l() then
        socket:send(">s|!+{TAB}|1<")
    end
    if pad:triangle() then
        socket:send(">d|1|1<")
        graphicsPrintln("Disconnected.")
        socket:close()
    end
    if pad:start() then
        socket:send(">d|1|1<")
        graphicsPrintln("Disconnected.")
        graphicsPrintln("Quit.")
        socket:close()
        break
    end
    screen.waitVblankStart()
end

Then your Autoit code will be:

Func _Recieve($ConnectedSocket)
While 1
; Try to recive up to 256 bytes.
    $Receive = TCPRecv($ConnectedSocket, 128)
    
; Use received data if given.
    If $Receive <> "" Then
        $command = StringSplit($Receive, ">") -- 
        For $number = 0 to UBound($command) -1
            If Not StringRegExp($command[$number] , ">([^<> .:ascii:]*?)<" , 0) Then
                ConsoleWrite("@@  --> Error processing command: " & $command[$number] & @LF)
                ContinueLoop();Ignoring...
            Else
                $command[$number] = StringReplace(StringReplace($command[$number] , ">" , "") , "<" , "")
            EndIf
            
            $avArray = StringSplit($command[$number], "|")
            $Type = $avArray[1]
            $Data1 = $avArray[2]
            $Data2 = $avArray[3]
            If $Type = "m" Then
                $pos = MouseGetPos()
                MouseMove($pos[0] + $Data1, $pos[1] + $Data2)
            ElseIf $Type = "c" Then
                MouseClick($Data1)
            ElseIf $Type = "d" Then
                TCPCloseSocket($ConnectedSocket)
                ExitLoop
            EndIf
        Next
    EndIf
WEnd
EndFunc

Note:

It looks like there is something wrong with my pattern in StringRegExp(), it doesn't work all the time, test it.

Let me know if that helped.

RK

Edited by rbhkamal

"When the power of love overcomes the love of power, the world will know peace"-Jimi Hendrix

Link to comment
Share on other sites

Works, except the following line:

If Not StringRegExp($command[$number] , ">([^<> .:ascii:]*?)<" , 0) Then

I had to change to:

If Not StringRegExp($command[$number] , "([^<> .:ascii:]*?)<" , 0) Then

Still gives me blank errors though (I changed the ConsoleWrite() to a traytip(), and it displays empty errors, but it still works). Script no longer disconnects when the disconnecting command is sent, and it still quits randomly after awhile (I've tried people's suggestions for debugging this, as well as my own, and I've gotten no where.)

It works much faster now. I think the main lagger this time is the Lua script, because it's sending packets with too many commands, and when the autoit script receives them, especially big ones, it will execute them all at once really fast, the way it should work. (So I need to figure out how to send smaller packets in Lua.)

BTW, the latest source code for everything can be found here: http://www.quate.net/link.php?pspmote

Edited by Slythfox
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...