Popular Post bogQ Posted October 14, 2012 Popular Post Posted October 14, 2012 (edited) This topic will contain simple and working client server communication example along with some basic info for understanding. Examples are based on multi client communication that is happening on one computer (localhost).Changing (if it's not already set correctly) the IP address parameter on server script to reflect your network device IP address will allow you to communicate with other clients on network or even to communicate on internet if your network settings (forwarded router port, ip address on that port is seen from others on internet, you're not trying to do client server from identical computer on identical internet connection) are configured correctly.Every client connecting will need to have server IP address for network (or server public IP address for internet) connection in his client script. So edit client script to correspond to server address TCPConnect('type server ip address in client', 1018). Sometimes firewall can be your problem, if something isn't working turn off firewall and see if it helps.Server will always listen on his Network Adapter IP Address and not on his public address. In some rare occasions server can be set to listen on 0.0.0.0, with that he will listen from any device that he have physically connected on his MB USB or something third (with localhost included for listening). But i would not know the end result of what will happen if some other program that you have installed need that port (or you started 2 servers that interpret one with another).First part will hold just plain code.Second part will hold identical code with comments below commands for more info and understanding hopefully to help new autoit users to understand what and why that something is there.Other parts will hold additional info.First part: Working Code (working in two way communication, with multiple and-or identical client)Server#include <Array.au3> TCPStartup() Dim $Socket_Data[1] $Socket_Data[0] = 0 $Listen = TCPListen(@IPAddress1, 1018, 500) If @error Then ConsoleWrite('!--> TCPListen error number ( ' & @error & ' ), look in the help file (on MSDN link) on func TCPListen to get more info about this error.' & @CRLF) Exit EndIf While 1 For $x = $Socket_Data[0] To 1 Step -1 $Recv = TCPRecv($Socket_Data[$x], 1000000) If $Recv Then MsgBox(0, 'Client Number ' & $x & ' with connected socket identifier ' & $Socket_Data[$x], 'Recived msg from Client: ' & @CRLF & $Recv, 5) TCPSend($Socket_Data[$x], 'bye') TCPCloseSocket($Socket_Data[$x]) _ArrayDelete($Socket_Data, $x) $Socket_Data[0] -= 1 EndIf Next _Accept() WEnd Func _Accept() Local $Accept = TCPAccept($Listen) If $Accept <> -1 Then _ArrayAdd($Socket_Data, $Accept) $Socket_Data[0] += 1 EndIf EndFunc ;==>_AcceptClient TCPStartup() $Socket = TCPConnect(@IPAddress1, 1018) If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ), look in the help file (on MSDN link) on func TCPConnect to get more info about this error.' & @CRLF) Exit EndIf TCPSend($Socket, 'Hi there. My computer name is' & ", " & @ComputerName & ", and its drive serial is " & DriveGetSerial(@HomeDrive)) Do $Recv = TCPRecv($Socket, 1000000) Until $Recv MsgBox(0, 'Recived from server:', $Recv)Second part: Explained Working Code (for upper communication)Serverexpandcollapse popup#cs * Learning about TCP servers and clients connection #ce #include <Array.au3> TCPStartup() #cs ! Starting up the server #ce Dim $Socket_Data[1] #cs * Wer declaring $Socket_Data array that will in future hold all sockets that connect to the server so that we can circle around trying to receive data from all connected sockets, next sockets will be added with _ArrayAdd used in our self created _Accept() function. * $Socket_Data array is declared with only one element, cos _ArrayAdd in func _Accept() will add new elements automatically and fill our $Socket_Data array. #ce $Socket_Data[0] = 0 #cs * We have 0 connections on the start, so arrayes first row (first element) will hold number of connections and on start we will set it to be = 0. #ce $Listen = TCPListen(@IPAddress1, 1018, 500) #cs * @IPAddress1 macro is your first network device found on your machine, to use some other device you can put it in format "xxx.xxx.xxx.xxx" eg "172.0.0.1" or use other @IPAddress* macros from help file. * 1018 is our port in this case, sometimes that specific port isn't free so it's a must to check if there is some error returned from TCPListen that can be because of wrong IP address or socket. * 500 is our MaxPendingConnections, it means that if new clients aren't added, only 500 of them can wait in line to be added, in most cases if you do expect a lot of clients this value should be set to smaller number, but in this case we will try to add 1 client on every "While 1" loop and we don't expect a lot of connections so there is not need to set this to something smaller. If you do and you're willing to add them in single loop that you need to consider looping $Accept until $Accept = -1, in that case i do advice for you to put this parameter to something smaller if you dont wish to lag out your server and kill your memory. #ce If @error Then ConsoleWrite('!--> TCPListen error number ( ' & @error & ' ), look in the help file (on MSDN link) on func TCPListen to get more info about this error.' & @CRLF) Exit EndIf #cs * @error will get last error from last func you used, in this case it will check error from upper func named TCPListen that we tried to call. So if error it will write out error number in your scite console and after that it will exit. #ce While 1 For $x = $Socket_Data[0] To 1 Step -1 #cs * Normal loop whud look like (For $x = 1 To $Socket_Data[0]), but cos we are using _ArrayDelete we will circle from bottom to the top in array so that we dont skip lines when deliting clients that we don't need anymore. #ce $Recv = TCPRecv($Socket_Data[$x], 1000000) #cs * $Socket_Data[$x] will hold socket identifier form array under current $x number trying to receive data from it and put it in $Recv variable. * 1000000 (in bytes if im not wrong) is our max amount of data we wish to receive. ! This doesn't mean that program will wait for specific amount of data before you receive something. ! This doesn't mean that you will receive only that specific amount of data and the rest is deleted. ! This mean that you will receive part of data on current TCPRecv call if its ower the max of 1000000 (do use some smaller walye 1000000 is only example), and the rest of data if any will wait for you when you call TCPRecv next time (the data is retained by the service provider until it is successfully read by calling TCPRecv with a large enough buffer). This shud mean that messages can mix itself, so you should always get some message separator between messages so that you know where some message starts and where it ends. ! For more info on how to split and rejoin one or more than one message, look at "Third Part" of this topic about some ideas. #ce If $Recv Then #cs * If we received something, the $Recv variable will hold that data, if it dont hold any data we will do nothing. #ce MsgBox(0, 'Client Number ' & $x & ' with connected socket identifier ' & $Socket_Data[$x], 'Recived msg from Client: ' & @CRLF & $Recv, 5) TCPSend($Socket_Data[$x], 'bye') #cs * It's your decision when to send client some answer. * In this case we will send him answer as soon as we check for and get his msg cos its easier as we already know that $Socket_Data[$x] to who we checked form msgs hold that socket identifier is probably still online. * In this case for testing wer using MsgBox to display results, in real life no one with common sense whud use msgbox for something like that cos msgbox can pause the script until it disappear. So on your real server if you have need to display results dont use msgbox, use Gui* commands that will not pause the script. #ce TCPCloseSocket($Socket_Data[$x]) _ArrayDelete($Socket_Data, $x) $Socket_Data[0] -= 1 #cs * It is your decision when to close some socket and don't accept any more data from him. * Here we are disconnecting socket as soon as we receive some msg and answer him. If we wanted for example to wait for something to happen before killing that socket we can put another trigger (If $Recv = 'bye im out' Then) and this will wait that specific data to be received before: - closing socket - deleting his identifier from array - reducing number of connection from current number with -1 * If we want to kill it on lets say time based interval then with usage of TimerDiff funcs we shud determan and disconnect that socket before we check if something is received, and skip reciving part from that point. * Just for explanation for some new user if reading this, about line ($Socket_Data[0] -= 1) its the same as dooing ($Socket_Data[0] = $Socket_Data[0] - 1), only difference is that it's sorter to write it like that. #ce EndIf Next _Accept() #cs * As i already tolded _Accept will check for new connections so we will call it once on every loop. #ce WEnd Func _Accept() #cs ! Self created _Accept func #ce Local $Accept = TCPAccept($Listen) If $Accept <> -1 Then _ArrayAdd($Socket_Data, $Accept) $Socket_Data[0] += 1 EndIf #cs * (If $Accept <> -1 Then) prakticly stands for pending new connection to add, and it should have (If Not @error Then) before it but as i don't expect errors here than i do think i don't need to complicate things alot more just for this example. * So wer adding new socket on next array line and wer increasing our connection count with +1. * If you do neeed to limit number of connection use (If $Socket_Data[0] < 500 Then) before checking for new connections and it will limit them to 500. #ce EndFunc ;==>_AcceptClient expandcollapse popup#cs * Learning about TCP servers and clients connection. #ce TCPStartup() #cs ! Starting up the client. #ce $Socket = TCPConnect(@IPAddress1, 1018) #cs * Connecting to IP address and port of server. ! In this case we are using on one computer communication, change IP address parameter to reflect server IP address if you need to go over lan. #ce If @error Then ConsoleWrite('!--> TCPConnect error number ( ' & @error & ' ), look in the help fule (on MSDN link) on func TCPConnect to get more info about this error.' & @CRLF) Exit EndIf #cs * Checking for error, write it down and exit on it. #ce #cs ! Constantly lopping (While 1) and dooing TCPSend when needed and TCPRecv ALL the time is correct way to go, but we will in this case just try to send some data and try to recive some msg before we exit the client. #ce TCPSend($Socket, 'Hi there. My computer name is' & ", " & @ComputerName & ", and its drive serial is " & DriveGetSerial(@HomeDrive)) #cs * So we gonna send some message to server. ! Note that just sending and exiting from client will not ensure that message is being received on server. If you do wish to send and exit try to put some sleep like 1 second before exiting the script to give server time to receive your last msg. Safer way is to wait for server to respond when he finished receiving your message so that you can send him new one or exit. * In this case we do not sleep but instead we lopping trying to receive last message before exiting cos we already know that server will dcc us after he sends us his msg. #ce Do $Recv = TCPRecv($Socket, 1000000) Until $Recv #cs ! It's always a good idea to put some time trigger on server for deleting socket if its not active after some predefined time. ! It's always a good idea to put some time trigger on client for exiting itself if server its responding after some predefined time. ! We're not checking for errors in TCPRecv or in TCPSend, it don't mean that they cant return errors. #ce MsgBox(0, 'Recived from server:', $Recv)Third Part: Understanding for how is msg received with TCPRecv on server (or on client)When ever client or server try to send you some data, is stored to something that we well call for now ($PortClientVariable).Every time new data arrives ($PortClientVariable) goes like this ($PortClientVariable = $PortClientVariable & $new_data).So our ($PortClientVariable) is always refilling itself with new data without deleting old data.Whenever you call TCPRecv to collect ALL data from ($PortClientVariable), ($PortClientVariable) do this:($PortClientVariable = Null)but only if recived data isn't larger than that predefined buffer size TCPRecv( mainsocket, maxlen)So it clears all data and empty it but not before you receive that data with TCPRecv.If its larger than predefined buffer size the data is retained by the service provider until it is successfully read by calling TCPRecv with a large enough buffer.If you sleep between the loop it doesn't do any difference, but if you receive 2 messages it do mean that you need to split them up (preferably you should use some char that you know your server and client will not use)One of the way (idea) to split and rejoin your recived msgs on server (or you can do something similar on client) ($ char is used on client as separator for messages that are send, array is used in 2D, first-one for client id-s, second-one for assinging each id its temp message) If $array[$r][0] <> "" Then $array[$r][1] = $array[$r][1] & TCPRecv($array[$r][0], 1000000) If $array[$r][1] <> "" Then $data = StringSplit($array[$r][1], "$") $even_odd = _MathCheckDiv($data[0], 2) If $even_odd = 2 Then For $x = 1 To $data[0] Step 2 _GUICtrlListView_InsertItem($hListView, $data[$x], 0) _GUICtrlListView_AddSubItem($hListView, 0, $data[$x + 1], 1, 1) Next $array[$r][1] = '' Else For $x = 1 To $data[0] - 1 Step 2 _GUICtrlListView_InsertItem($hListView, $data[$x], 0) _GUICtrlListView_AddSubItem($hListView, 0, $data[$x + 1], 1, 1) Next $array[$r][1] = $data[$data[0]] EndIf EndIf EndIfThat mean, after every received message you need to join up old data with new data to determine what part of msg did you get, or you can make that client or server won't send new data until server responded that he received something from start of data to end of data (witch is more safer way in some cases of dooing it)Note that large sleep can cause killing of your memory and lagging out your server (or client), so i don't recommend it.Forth Part: PacketsYour speed and device is your limitation, as for its max sizehttp://en.wikipedia.org/wiki/Maximum_transmission_unitLarge packets can occupy a slow link for some time, causing greater delays to following packets and increasing lag and minimum latency. For example, a 1500-byte packet, the largest allowed by Ethernet at the network layer (and hence over most of the Internet), ties up a 14.4k modem for about one second.Fifth Part: How to get or check IP address of your device?From start meny sellect run (or in win 7 just tupe cmd and hit enter with no run) tupe in cmd and press enter. After that in cmd type ipconfig and press enter.It will list all of your adapters and their ip (IPv4) addresses.Sixth Part: How to forward ports? (2 nice youtube tutorials)Check if your ports are already forwarded onhttp://www.yougetsignal.com/tools/open-ports/orhttp://www.canyouseeme.org/If not, then this 2 videos are your guide.http://www.youtube.com/watch?v=Kp-R-eHiQco&feature=player_embeddedhttp://www.youtube.com/watch?feature=player_embedded&v=vFHVeWNP9SkSeventh Part: Internet communication?IF YOUR RUNNING CLIENT AND SERVER ON IDENTICAL INTERNET CONNECTION DON'T GET YOUR HOPES UP THAT INTERNET COMMUNICATION WILL WORK!!!INSTEAD THAT, WHEN YOU HAVE ALL SETUP CORRRECTLY (PORTS FORWARDED AND EVERYTHING), CALL SOME FRIEND AND TELL HIM TO RUN YOUR CLIENT FOR TESTING!!!Let's say we have computer that will be our server with public IP address (for example)77.170.181.98How to check your ip? Go tohttp://www.whatismyip.com/On client, we don't need to know client ip address, but he need to know server public IP address that is 77.170.181.98 in this example.Server do TCPListen on his adapter IP address. That address isn't 77.170.181.98, we need adapter address that i explained how to get on Fifth Part of this topic. In this case we will use 10.0.252.30 as example. Ports must be forwarded on router so that he can send all traffic to your network device.So client connect to 77.170.181.98 server public IP address.And server listen on network device address 10.0.252.30.They both trigger identical port in this case :8080.Lets see whats happening inside:-----------------------------------*Client try to connect to server*Client send msg to public IP address77.170.181.98:8080 -> "are you there?"*router recive msg on ip address 77.170.181.98 for port 8080 and forward it on that port to your listening device 10.0.252.30 Client -> Connect public IP -> Listening Device -> server recive msg Dont need client ip -> 77.170.181.98:8080 -> 10.0.252.30:8080 -> "are you there?"-----------------------------------If i wrote something incorrectly or wrong please tell me so that i can correct it.Edited: Local and Global, added aditional info about reciving msgs for maxlen buffer. Edited June 5, 2014 by bogQ Xandy, JohnOne, Gianni and 3 others 6 TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
guinness Posted October 14, 2012 Posted October 14, 2012 Nice tutorial. You should probably look at using variable declaration in your examples. For example your Global declaration should be Local as the variable isn't used anywhere else but in Local scope. UDF List: _AdapterConnections() • _AlwaysRun() • _AppMon() • _AppMonEx() • _ArrayFilter/_ArrayReduce • _BinaryBin() • _CheckMsgBox() • _CmdLineRaw() • _ContextMenu() • _ConvertLHWebColor()/_ConvertSHWebColor() • _DesktopDimensions() • _DisplayPassword() • _DotNet_Load()/_DotNet_Unload() • _Fibonacci() • _FileCompare() • _FileCompareContents() • _FileNameByHandle() • _FilePrefix/SRE() • _FindInFile() • _GetBackgroundColor()/_SetBackgroundColor() • _GetConrolID() • _GetCtrlClass() • _GetDirectoryFormat() • _GetDriveMediaType() • _GetFilename()/_GetFilenameExt() • _GetHardwareID() • _GetIP() • _GetIP_Country() • _GetOSLanguage() • _GetSavedSource() • _GetStringSize() • _GetSystemPaths() • _GetURLImage() • _GIFImage() • _GoogleWeather() • _GUICtrlCreateGroup() • _GUICtrlListBox_CreateArray() • _GUICtrlListView_CreateArray() • _GUICtrlListView_SaveCSV() • _GUICtrlListView_SaveHTML() • _GUICtrlListView_SaveTxt() • _GUICtrlListView_SaveXML() • _GUICtrlMenu_Recent() • _GUICtrlMenu_SetItemImage() • _GUICtrlTreeView_CreateArray() • _GUIDisable() • _GUIImageList_SetIconFromHandle() • _GUIRegisterMsg() • _GUISetIcon() • _Icon_Clear()/_Icon_Set() • _IdleTime() • _InetGet() • _InetGetGUI() • _InetGetProgress() • _IPDetails() • _IsFileOlder() • _IsGUID() • _IsHex() • _IsPalindrome() • _IsRegKey() • _IsStringRegExp() • _IsSystemDrive() • _IsUPX() • _IsValidType() • _IsWebColor() • _Language() • _Log() • _MicrosoftInternetConnectivity() • _MSDNDataType() • _PathFull/GetRelative/Split() • _PathSplitEx() • _PrintFromArray() • _ProgressSetMarquee() • _ReDim() • _RockPaperScissors()/_RockPaperScissorsLizardSpock() • _ScrollingCredits • _SelfDelete() • _SelfRename() • _SelfUpdate() • _SendTo() • _ShellAll() • _ShellFile() • _ShellFolder() • _SingletonHWID() • _SingletonPID() • _Startup() • _StringCompact() • _StringIsValid() • _StringRegExpMetaCharacters() • _StringReplaceWholeWord() • _StringStripChars() • _Temperature() • _TrialPeriod() • _UKToUSDate()/_USToUKDate() • _WinAPI_Create_CTL_CODE() • _WinAPI_CreateGUID() • _WMIDateStringToDate()/_DateToWMIDateString() • Au3 script parsing • AutoIt Search • AutoIt3 Portable • AutoIt3WrapperToPragma • AutoItWinGetTitle()/AutoItWinSetTitle() • Coding • DirToHTML5 • FileInstallr • FileReadLastChars() • GeoIP database • GUI - Only Close Button • GUI Examples • GUICtrlDeleteImage() • GUICtrlGetBkColor() • GUICtrlGetStyle() • GUIEvents • GUIGetBkColor() • Int_Parse() & Int_TryParse() • IsISBN() • LockFile() • Mapping CtrlIDs • OOP in AutoIt • ParseHeadersToSciTE() • PasswordValid • PasteBin • Posts Per Day • PreExpand • Protect Globals • Queue() • Resource Update • ResourcesEx • SciTE Jump • Settings INI • SHELLHOOK • Shunting-Yard • Signature Creator • Stack() • Stopwatch() • StringAddLF()/StringStripLF() • StringEOLToCRLF() • VSCROLL • WM_COPYDATA • More Examples... Updated: 22/04/2018
caleb41610 Posted October 14, 2012 Posted October 14, 2012 I'm sure this will help a lot of people who are new to TCP! I would love to see an example as detailed as this about maintaining multiple connections! Multi-Connection TCP Server
bogQ Posted October 14, 2012 Author Posted October 14, 2012 (edited) server is already set to handle more than 1 connection, you just need to: get rid of msgbox (use gui commands instead) that pause server limit if needed numebr of connection that it will handle change how and when will server disconnect clients Read server part with explained code for more info. Edited October 14, 2012 by bogQ TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
Hubert24 Posted October 22, 2012 Posted October 22, 2012 Thanks for the code and tutorial, helpful codes. let me start by saying i am a beginner, so please don't laugh too at my questions! 1. with your codes, I have to run the server and client codes on every PC connected on my network. is there a possibility that I might run the codes for server just once and on the other PCs, i will just have to run but the codes for clients? 2. I wish to have 3 or more Computers, the first computer is my master, where my server runs, the other computers are my client. I wish to send message in both dirrection via TCP as is the case with your codes how am I going to do it? 3. I have tried to open TCP socket via internet but all my attemps have failed. my internet IPaddress is 192.168.1.1 I will be grateful if you find time and provide me some helps. Best regards Hubert
bogQ Posted October 22, 2012 Author Posted October 22, 2012 (edited) Guess i need to add litle more info about networks on first postlets expalind it heare like thisI have 2 computers and i need to do TCP over wireless network.My first computer (he will be server) need to lissen on my second adapter (my first adapter is lan, my second adapter is wireless card), he (wirelles card) is with IP adress @IPAddress2 or 192.168.0.1 (@IPAddress2 is my wireless adapter IP that i manyaly tuped on adapter)my second computer that have only client on him is with ip address 192.168.0.2 on his wireless lan card and he is connected over that card to my wireless card so that we can be in network, but his IP is not important cos i only need to know server IP adress 192.168.0.1 so that i can connect on him.so on server im starting it with$Listen = TCPListen(@IPAddress2, 1018, 500)or with $Listen = TCPListen('192.168.0.1', 1018, 500), it is identical cos @IPAddress2 will return (in my case) IP address of my second device 192.168.0.1and on client script im putting$Socket = TCPConnect('192.168.0.1', 1018)so im connection on IP adress of server with clientnow let's say that i wanna connect more than one pc but not on my wireless network cos it accept only 2 computers, i wanna do it on lan network adapter (my first lan device), on lan i have 6 PC-s connected on network.My first comp is with ip adress lets say 10.0.252.30 on my local area connection adapter.How can i confirm that my ip is 10.0.252.30?! From start meny i sellect run (or in win 7 just tupe cmd and hit enter with no run) tupe in cmd and press enter. after that in cmd i type in ipconfig and press enter.it will list all of your adapters and their ip (IPv4) addresses.So im gona start server on my network lan adapter$Listen = TCPListen('10.0.252.30', 1018, 500)and every client i connect on him will connect to that ip adressso on client im dooing this$Socket = TCPConnect('10.0.252.30', 1018)So i will connect more than one client and only one comp (my first comp) will serve as my server.Note that somethimes firewall can cose problems, so if you have problems turn it off to see if it will work.As for internet communication i can't help a lot, i never tried coz my ports are forwarded. Main thing i know is if your behind router form your ISP and your ports arn't forwarded you need to call your ISP on the phone and to tell him to forward that darn port and don't hang up till he say "ok i forwarded it".If router is in your controll, don't call ISP, take a look at this videos (they are nice tytorials)and do it yourself here you can check if others can see you on that porthttp://www.yougetsignal.com/tools/open-ports/orhttp://www.canyouseeme.org/ Edited October 22, 2012 by bogQ TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
coffeeturtle Posted October 23, 2012 Posted October 23, 2012 (edited) Thank you bogQ for this terrific tutorial! The time you put into this is very much appreciated! Great work! Would you be okay with taking this to the next level? -Adding GUI instead of Msgbox -Having one script work as both server and client to create an Instant Messaging program -Adding Contact List of all machines that are connected (listed as IP address or @ComputerName This would probably be a big project, but written in the style that you have already done would be of great help. I figure it never hurts to ask and certainly you've given us a great base of understanding to work from. Thank you again! Edited October 23, 2012 by coffeeturtle
ludocus Posted November 11, 2012 Posted November 11, 2012 Thnx for your helpful topic.I have a question though. I would like to use TCP to connect (lets say) 2 computers but in different houses. So different IP adresses.So the connection should go via WAN, not LAN. How can I make my real IP adress, like 77.170.181.98, serve as a server?Thnx in advance
bogQ Posted November 11, 2012 Author Posted November 11, 2012 (edited) Guess someone with more experience with internet communication should answer this one but if im wrong they can still correct me or at least confirm if this is correct (as i stated before "i can't help a lot, i never tried coz my ports are forwarded") So "if im not wrong", one computer is server, his public IP address is 77.170.181.98 one client, we dont need to know his ip adress, but he need to know server public IP address. Server TCPListen on his addapter IP adress (so that isnt 77.170.181.98, we need adapter address) (port must be forwarded on router) Client connect to 77.170.181.98 server public IP adress. So client try to connect to server *Client send msg to server ip adress 77.170.181.98:8080 -> "are you there?" *router recive msg for port 8080 and forward it on that port to your listening device 10.0.252.30 ->77.170.181.98:8080 -> 10.0.252.30:8080 -> "are you there?" Edited November 11, 2012 by bogQ TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
caleb41610 Posted November 12, 2012 Posted November 12, 2012 (edited) that's basically how it works. i just use TCPListen("0.0.0.0", 8080) and it automatically listens on your default adaptor. no need to even get lan/wan ip on the server. on the router, forward 8080 to your local server ip. on the client, connect to the servers WAN. or use @IPAddress1 instead of 0.0.0.0. either should work fine. edit: 0.0.0.0 makes it listen on "any available" ip, so it will work with multiple adaptoras, i believe. Edited November 12, 2012 by caleb41610 Multi-Connection TCP Server
ludocus Posted December 1, 2012 Posted December 1, 2012 Ok thnx for the info.It is still not working though.This is a picture of the port I forwarded (is this right??):And then this is the server script line:$Listen = TCPListen('192.168.2.8', 8080, 500)And this is the client's line:$Socket = TCPConnect('77.170.181.98', 8080)This should be good, right?It is not working though, please tell me if I did something wrong
bogQ Posted December 1, 2012 Author Posted December 1, 2012 as i told my isp did not forwarded my ports so i can testin theory it should worki posted 2 links in first posthttp://www.yougetsignal.com/tools/open-ports/orhttp://www.canyouseeme.org/so can they see you on port 8080?another question is , is your port 8080 free? no other program is using him?did you try on some other port? is your wirewall off? TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
caleb41610 Posted December 2, 2012 Posted December 2, 2012 Ok thnx for the info. It is still not working though. This is a picture of the port I forwarded (is this right??): And then this is the server script line: $Listen = TCPListen('192.168.2.8', 8080, 500) And this is the client's line: $Socket = TCPConnect('77.170.181.98', 8080) This should be good, right? It is not working though, please tell me if I did something wrong You must also open the port in your firewall. Multi-Connection TCP Server
ludocus Posted December 5, 2012 Posted December 5, 2012 (edited) Ok still now working.I changed to port 8081 (just to be sure the port wasn't used by anything else)I also opened 8081 on my windows firewall.I checked with the port website, and it says the port is open (if the server is running):As you see, the port is open.Now when I run the client, I get the following error:!--> TCPConnect error number ( 10060 ), look in the help file (on MSDN link) on func TCPConnect to get more info about this error.BTW: I'm running the client and server on the same pc (thus same ip adress). Could this be causing my trouble?I've been trying to make this work for ages now, please help me out once more!Thnx Edited December 5, 2012 by ludocus
bogQ Posted December 5, 2012 Author Posted December 5, 2012 (edited) yes it can, if you ever had experience with wamp server or wow servers for example, you couldn't never connect to the site or gameserver on internet connection ip adress from the computer that is running that server, but you can go to that adress if you go to some proxy with browser site and connecting with it with no problems.so WSAETIMEDOUT 10060 Connection timed out. A connection attempt failed because the connected party did not properly respond after a period of time, or the established connection failed because the connected host has failed to respond. can be cuz of that, and in addition it can be cuz of port problem, or something third.So please do try to connect with 2 different computers with 2 different internet connection on them. (call some friend and tell him to run your client)if it dont work try some other random ports eg 3724 8129 28960...and try to lisssen on ip 0.0.0.0for some other info to "can it realy work" you can look at this post to see that TCP do work on internet if everything is configyred in the correct way and your isp isnt playing with you.http://en.wikipedia.org/wiki/List_of_TCP_and_UDP_port_numbers Edited December 5, 2012 by bogQ TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
bogQ Posted December 18, 2012 Author Posted December 18, 2012 just a quick note from my side, after i convince my isp to geave me some free ports for next month, i tryed to connect over internet on port 8080 today to test do it work or not tcp lisen on 0.0.0.0 and after that on @IPAddress1 with port 8080, connected to server public IP and message recived, sended, and recived with no problems port 80 did have probably cos my wamp did use it when i try it on. So it do work with no problem if everything is configured correctly. TCP server and client - Learning about TCP servers and clients connectionAu3 oIrrlicht - Irrlicht projectAu3impact - Another 3D DLL game engine for autoit. (3impact 3Drad related) There are those that believe that the perfect heist lies in the preparation.Some say that it’s all in the timing, seizing the right opportunity. Others even say it’s the ability to leave no trace behind, be a ghost.
TurionAltec Posted July 20, 2016 Posted July 20, 2016 (edited) Excellent. This was exactly what I needed. I have another script I'm building that's generating text output. I wanted to be able to call a separate script running a TCP server, pass the data over Stdin, and have the Server duplicate out whatever data is was sent to whatever clients are connected at the time, and manage listening, opening, and closing Sockets. I have something like this compiled to .EXE, though if running as an .au3 file, it will prompt you with an Input box for data to send. Connect and disconnect as many Telnet (Putty, Teraterm) sessions as you want and they start getting output. expandcollapse popup#include <Array.au3> #include <WinAPIProc.au3> ;Ref https://www.autoitscript.com/forum/topic/144987-learning-about-tcp-servers-and-clients-connection/ $ParentPID = _WinAPI_GetParentProcess() TCPStartup() OnAutoItExitRegister("OnAutoItExit") Dim $Socket_Data[1] $Socket_Data[0] = 0 $Listen = TCPListen("0.0.0.0", 1018, 500) If @error Then ConsoleWrite('!--> TCPListen error number ( ' & @error & ' ), look in the help file (on MSDN link) on func TCPListen to get more info about this error.' & @CRLF) Exit EndIf While ProcessExists($ParentPID) If @Compiled=0 Then $TCPdata=InputBox("TCPServer","Type Data to send") Else $TCPData = ConsoleRead() EndIf If StringLen($TCPData) > 0 Then For $x = $Socket_Data[0] To 1 Step -1 TCPSend($Socket_Data[$x], $TCPData) If @error Then _CloseConnection() EndIf Next EndIf _Accept() Sleep(500) WEnd Func _Accept() Local $Accept = TCPAccept($Listen) If $Accept <> -1 Then _ArrayAdd($Socket_Data, $Accept) $Socket_Data[0] += 1 EndIf EndFunc ;==>_Accept Func _CloseConnection() _ArrayDelete($Socket_Data, $x) $Socket_Data[0] -= 1 EndFunc ;==>_CloseConnection Func OnAutoItExit() TCPShutdown() ; Close the TCP service. EndFunc ;==>OnAutoItExit I then use this script to establish the link to Stdin: #include <AutoItConstants.au3> $iPID = Run("tcpserver.exe", "", @SW_HIDE, $STDIN_CHILD) While 1 $Data=InputBox("Input","data") StdinWrite($iPID,$Data) Wend Edited July 20, 2016 by TurionAltec Gianni 1
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now