Jump to content
Sign in to follow this  
JonBMN

[SOLVED]Sending Line over TCP connection from two clients

Recommended Posts

JonBMN

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
JonBMN

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
FireFox

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
JonBMN

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
JonBMN

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  

  • Similar Content

    • Rskm
      By Rskm
      Hi, for a script of mine, I wish to keep a time frame on till how the program will work.. basically, I want the program to read the date and if the read date < 'a particular date', the program continues, else it exit. I don't want to read the time from the computer as the program can be fooled by resetting the pc time. is there a way to read time from internet - so that the user cannot fool the program by date reset? thanks
    • Spartan117
      By Spartan117
      Hi everyone,
      I wonder if there is a cloud service that can offer a physical server so that AutoIT can turn as it is in a physical machine.
      Thank you
    • ur
      By ur
      I have an aws cloud machine where I kept all the build process to create some set of zip files and uploading them to OneDrive.
      Once it is completed, I have another local machine in our environment which is a acting as a local share server also.
      Is there anyway to notify this machine(without public IP) to start downloading these files.
      I have written an AutoIT exe to download these files and copy them to respective locations.But don't know how to notify this from the remote machine.
       
      Any suggestion??
       
    • Nareshm
      By Nareshm
      Its Possible To auto Login with autoit script ?
    • 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.
       
×