Sign in to follow this  
Followers 0
JonBMN

[SOLVED]Sending Line over TCP connection from two clients

5 posts in this topic

#1 ·  Posted (edited)

I'm trying to create two sides; A client side and a server side. I've got each one to work and send data from the client to the server, but if two clients are sending data at the same time. I would like to be able to get both and not just have one send while the other one gets ignored. Is there anyway I can implement a buffer so that when one connection gets done the other then starts receiving from the second client?

Here is my code.

~Client Side~

TCPStartup()

HotKeySet("{Esc}", "Quit")

Local $ip, $port, $data, $connect

$ip = "*servers IP address here*"
$port = 21230

$connect = TCPConnect($ip, $port)
If @error Then
    ConsoleWrite("Could not connect to " & $ip)
    sleep(1000)
    Quit()
EndIf

message()
;ConsoleWrite($data)




Sleep(3000)
Quit()


Func message()
    Local $File, $Line = "", $i = 0, $EOF = ""
    $File = FileOpen("tcpexample.txt", 0)
    If $File = -1 Then
        MsgBox(0, "Error", "Unable to read the file.")
        Exit
    EndIf
  Do
     $Line = FileReadLine($File)
     $EOF = @error
     ConsoleWrite($Line & @CRLF)
     TCPSend($connect, $Line)
     If @error Then
        ConsoleWrite("There was an error sending." & @CRLF)
     EndIf
     sleep(500)
   Until $EOF = -1
    FileClose($File)
EndFunc


Func Quit()
    TCPShutdown()
    Exit
EndFunc

~Server Side~

TCPStartup()
HotKeySet("{Esc}", "Quit")
Local $ip, $port, $Accept, $Listen, $AcceptError = True, $Result
$Result = FileOpen("tcptest.txt", 1)

$ip = @IPAddress1;try $IPAddress2/3/4 if this doesn't work
$port = 21230

$Listen = TCPListen($ip, $port)
If ($listen = - 1 or $listen = 0) and (@error = 1 or @error = 2) Then
    ConsoleWrite("TCPListen returned @error: " & @error)
    Quit()
EndIf


While 1
    If $AcceptError = True Then
        AcceptConnection()
    EndIf
    If $AcceptError = False Then
        $recv = ""
        $recv = TCPRecv($Accept, 1024)
        If @Error Then
          ConsoleWrite("Connection timed out: " & $Accept & @CRLF)
          $AcceptError = True
        EndIf
    If $recv <> "" Then
        FileWriteLine($Result, $recv)
        ConsoleWrite("We received this: " & $recv & @CRLF)
        EndIf
    EndIf
WEnd




Func Quit()
    TCPShutdown()
    FileClose($Result)
    Exit
EndFunc

Func AcceptConnection()
    $AcceptError = True
    While 1
        $Accept = TCPAccept($Listen)
        If $Accept <> -1 Then
            ConsoleWrite($accept & " has connected" & @CRLF)
          $AcceptError = False
            ExitLoop
        EndIf
    WEnd
EndFunc
Edited by JonBMN

Share this post


Link to post
Share on other sites

I figured out a way to make it so there is a buffer, by putting in TCPListen($ip, $port, 100) 100 connections to wait for at the end of TCPListen. This shoves them all together and gives me one big string, which is not what I want.

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Hi,

The TCPAccept function returns a socket identifier which corresponds to a client.

You need to store them in an array, then loop through it and use the TCPRecv function.

Edit: There is some examples available in the forum.

Br, FireFox.

Edited by FireFox

 

OS : Win XP SP2 (32 bits) / Win 7 SP1 (64 bits) / Win 8 (64 bits) | Autoit version: latest stable / beta.
Hardware : Intel(R) Core(TM) i5-2400 CPU @ 3.10Ghz / 8 GiB RAM DDR3.

My UDFs : Skype UDF | TrayIconEx UDF | GUI Panel UDF | Excel XML UDF | Is_Pressed_UDF

My Projects : YouTube Multi-downloader | FTP Easy-UP | Lock'n | WinKill | AVICapture | Skype TM | Tap Maker | ShellNew | Scriptner | Const Replacer | FT_Pocket | Chrome theme maker

My Examples : Capture toolIP Camera | Crosshair | Draw Captured Region | Picture Screensaver | Jscreenfix | Drivetemp | Picture viewer

My Snippets : Basic TCP | Systray_GetIconIndex | Intercept End task | Winpcap various | Advanced HotKeySet | Transparent Edit control

 

Share this post


Link to post
Share on other sites

Thanks FireFox,

I've also been playing around with a couple examples and seeing how they work so will be posting in this forum as progression happens.

really helpful, but full of example client side and server side scripts that are not working correctly, but great examples nonetheless.

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

Here is my solution to this particular question/topic. I've changed around the code and I'm using the above example from kip's topic with modified scripts for both server and client.

This will take a .txt and push the lines of text from the client side to the server side and write the received from the client side into a new .txt file. Now for multiple clients I'm still working on making it clean, but this is the shell and can be used very easily and made into a multi-client system. Which I'm in the process of making it clean and able to sort itself, but here is my code...

~Client-side~

#include "TCP.au3"

SendTxt()

Func SendTxt()
    Local $Txt, $Line = "", $EOF = "", $stcp
    $Txt = FileOpen("example.txt", 0)
    If $Txt = -1 Then
         MsgBox(0, "Error", "Unable to read the file.")
         Exit
    EndIf
  Do
     HotKeySet("{Esc}", "Quit")
     $hClient = _TCP_Client_Create("192.168.1.103", 21230); Create the client. Which will connect to the local ip address on port 21230
     sleep(1000)
     _TCP_RegisterEvent($hClient, $TCP_RECEIVE, "Received"); Function "Received" will get called when something is received
     _TCP_RegisterEvent($hClient, $TCP_CONNECT, "Connected"); And func "Connected" will get called when the client is connected.
     _TCP_RegisterEvent($hClient, $TCP_DISCONNECT, "Disconnected"); And "Disconnected" will get called when the server disconnects us, or when the connection is lost.
     $Line = FileReadLine($Txt)
     $EOF = @error
     ConsoleWrite($Line & @CRLF)
     If $Line <> "" Then
        $stcp = TCPSend($hClient, $Line)
     EndIf
     If @error Then
        ConsoleWrite("There was an error sending." & $stcp & @CRLF)
     EndIf
     ;sleep(1000)
     TCPCloseSocket($hClient)
   Until $EOF = -1
    FileClose($Txt)
    SendTxt()
EndFunc

Func Connected($hSocket, $iError); We registered this (you see?), When we're connected (or not) this function will be called.
    If not $iError Then; If there is no error...
        ;ToolTip("CLIENT: Connected!",10,10); ... we're connected.
    Else; ,else...
        ;ToolTip("CLIENT: Could not connect. Are you sure the server is running?",10,10); ... we aren't.
    EndIf
EndFunc


Func Received($hSocket, $sReceived, $iError); And we also registered this! Our homemade do-it-yourself function gets called when something is received.
    ;ToolTip("CLIENT: We received this: "& $sReceived, 10,10); (and we'll display it)
EndFunc

Func Disconnected($hSocket, $iError); Our disconnect function. Notice that all functions should have an $iError parameter.
    ;ToolTip("CLIENT: Connection closed or lost.", 10,10)
EndFunc

;~Thanks Kip~;

~Server-Side~

#include "TCP.au3"

;ToolTip("SERVER: Creating server...",10,30)

$hServer = _TCP_Server_Create(21230); A server. Tadaa!


_TCP_RegisterEvent($hServer, $TCP_NEWCLIENT, "NewClient"); Whooooo! Now, this function (NewClient) get's called when a new client connects to the server.
_TCP_RegisterEvent($hServer, $TCP_DISCONNECT, "Disconnect"); And this,... this will get called when a client disconnects.
_TCP_RegisterEvent($hServer, $TCP_RECEIVE, "Receive"); And this,... when we receive something from the client side

While 1
    HotKeySet("{Esc}", "Quit")
WEnd

Func NewClient($hSocket, $iError); Yo, check this out! It's a $iError parameter! (In case you didn't noticed: It's in every function)
    ;ToolTip("SERVER: New client connected."&@CRLF&"Sending this: I see you...",10,30)
    _TCP_Send($hSocket, "I see you..."); Sending: "Bleh!" to the new client. (Yes, that's right: $hSocket is the socket of the new client.)
EndFunc

Func Disconnect($hSocket, $iError); Damn, we lost a client. Time of death: @Hour & @Min & @Sec :P
    ;ToolTip("SERVER: Client disconnected.",10,30); Placing a tooltip right under the tooltips of the client.
EndFunc

Func Receive($hSocket, $sReceived, $iError)
    Local $Txt = FileOpen("tcpexample.txt", 1)
    ;ConsoleWrite($sReceived & @CRLF)
    _TCP_Send($hSocket, "I got that...")
    ;ToolTip("SERVER:Sending To:" & $hSocket & @CRLF & "Sending this: I got that...", 10, 30)
    ;ToolTip("SERVER:" & $hSocket & " Connected" & @CRLF, 10, 30)
    If $sReceived <> "" Then
        FileWriteLine($Txt, $sReceived & @CRLF)
        ConsoleWrite("We received this: " & $sReceived & @CRLF)
    EndIf
    FileClose("tcpexample.txt")
EndFunc

Func Quit()
    Exit
EndFunc


;~Thanks Kip~;
Edited by JonBMN

Share this post


Link to post
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
Sign in to follow this  
Followers 0

  • Similar Content

    • ripdad
      By ripdad
      I have had several people ask for this, so I decided to work the algorithm for it and this is the result.
      What is it?
      A Gateway Proxy Sends and Receives Data Unmodified.
      https://en.wikipedia.org/wiki/Proxy_server
      What is it used for?
      You can use it as a gateway, relay or router between two known static IP addresses.
      More information is in the header of the script.
      Download: LocalGatewayProxy.au3
      You will need WSA_NBTCP.au3 from here:
      https://www.autoitscript.com/forum/topic/191954-wsa_nbtcp-v100-udf/
      If you have any questions or problems, let me know.
       
    • ripdad
      By ripdad
      This script is based on algorithm code from EnrMa.
      Updated: January 22, 2018
      Made improvements. Changes are in the script header.
      Known Issues: AutoIt x64 does not work properly with this script.
      Download: LocalProxyServer_v1.00.zip
       
    • ripdad
      By ripdad
      WSA_NBTCP.au3  (Windows Sockets API - Non-Blocking Transmission Control Protocol)
      Version: 1.00
      Type: UDF
      This is an accumulation of WSA code from many sources and modified to suit myself.
      These functions have been thoroughly tested using a Local Proxy Server, which
      is about the most strenuous test you can use.
      Includes my rendition of how a TCPRecv Timeout should work. Also includes a
      timewait/timeout using Select for TCP Send, which works great for that function.
      You will need a loop to use _WSA_TCPRecv(). An example will be forthcoming in a second post.
      Functions:
      #CURRENT_USER_FUNCTIONS
      _WSA_Cleanup
      _WSA_FormatMessage
      _WSA_GetLastError
      _WSA_TCPAccept
      _WSA_TCPCloseSocket
      _WSA_TCPConnect
      _WSA_TCPListen
      _WSA_TCPRecv
      _WSA_TCPSend

      #INTERNAL_FUNCTIONS
      __TimeoutManager
      __TimeoutReset

      #EXTRA_FUNCTIONS
      _WSA_GetAddrInfo
      _WSA_GetHostByAddr
      _WSAAsyncGetHostByName
      _WSAAsyncGetHostByName_Callback
      _WSA_GetNameInfo
       
      Requirements:
      - AutoIt Versions: 3.3.8.1 thru 3.3.15.0 (32Bit only).
      - TCPStartup() at beginning of script on startup.
      - TCPShutDown() and _WSA_Cleanup() on exit.
      Download UDF: WSA_NBTCP.au3
       
    • tarretarretarre
      By tarretarretarre
      AutoIt-SocketIo
      Yep yep, this is pretty much an attempt to port the existing project's concept https://socket.io/ to AutoIt's Codebase. So i will not go in to so much detail.
      This is how the communication is done http://i.imgur.com/0mMfsBD.png Each client is isolated to the server http://i.imgur.com/rVO2LFb.png Features
      Easy API VarType Translation (Example: If the server sends an int, the client will receive an int and vice versa) Fully featured examples Data encryption (Using Autoit's UDF Crypt.au3) Limitations / Drawbacks
      It is not possible to Broadcast/Emit objects Only 1D-arrays are allowed to be Broadcasted/Emitted (2D arrays will probably never be supported) Changelog
      Version 1.5.0 (This update DOES NOT break scripts)
      Added AutoIt like docs under Docs\. The docs are generated so its a 1 to 1 reflection of the UDF headers. Print of documentation Added a production ready server example. Added a new method: _Io_DevDebug which will display useful information when debugging. Added a new method: _Io_SetMaxRecvPackageSize which defaults to whatever _Io_setRecvPackageSize is set to. Added a new method: _Io_setOnPrefix which defaults to _On_ Added a new default client & server event called flood. Flood occurs when exceeding the $__g_io_nMaxPacketSize. $__g_io_nMaxPacketSize is set by _Io_SetMaxRecvPackageSize Fixed the 16 parameter limit when sending data with _Io_Emit, _Io_Broadcast, _Io_BroadcastToAll and _Io_BroadcastToRoom. This works on the same premise that AutoIt's Call Does Fixed a TRUNCATION problem when receiving packages which could cause crashes! Fixed a programming error which caused $__g_ionPacketSize to reset to default 4096 if _Io_Connect or _Io_listenwere called after _Io_setRecvPackageSize Fixed _Io_setEventPreScript and _Io_setEventPostScript They didnt work. Lol. Changed how events are fired so the client cannot crash the server by sending the wrong number of parameters (This also allows for optional parameters on callbacks) Changed _Io_On. The second parameter $fCallback can now be set to null. Doing this, the function assumes that the callback is: _On_<eventName>.  
      Changelog History
      Api methods
      Please see the docs provided
      Default events
      Server events
      connection Client events
      banned Server and Client events
      disconnect flood View source on github
       
      Autoit-Socket-IO-1.0.0.zip (OLD!)
      Autoit-Socket-IO-1.1.0.zip (OLD)
      Autoit-Socket-IO-1.3.0.zip (OLD)
      Autoit-Socket-IO-1.4.0.zip (OLD)
      Autoit-Socket-IO-1.5.0.zip (NEWEST 2017-12-20)
    • Pintu
      By Pintu
      Good evening guys,
      i'm having a problem, not about the code (i'm only thinking about it at the moment) but about the way i can do it.
      I have a webpage (photo N.1) it has some elements in it.
      I need only the table (photo N.2), looking at the code and with _IEFunctions i can easy find the table but how i can i "copy" it?
      As i said it's really easy to found with a script but what should i do then? Copy the source? And how can i display it to the user?
      In my head i'd like to display it inside a GUI, is that possible?
       
      Thanks in advance
       
      Edit: Posted 2 times same photo. Now should be OK