April 23, 2024, 07:11:28 PM

News:

Own IWBasic 2.x ? -----> Get your free upgrade to 3.x now.........


UDP code

Started by Ionic Wind Support Team, April 20, 2009, 11:27:27 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Ionic Wind Support Team

Some older UDP code I found lying around on my HD.  Might be useful to someone, compiles as-is with Emergence BASIC.


'UDP "PC-to-PC" Network program for IBPro, written by Valentin Angelovski 15/1/2005
'Version 2.0  ***  Converted to IbasicPro on 16th Feb 2005 ***
'Version 3.0  ***  corrected for an over-zealous error-checking routine ***
'I have tested this code and have found the winsock functions to work,
'feel free to experiment with this code as you see fit, so long as...
'You accept this program 'as-is' ie: use it at your own risk!
'
'   The following SIX subroutines and their functions are desbribed below:
'
' startup() - Initialises ie: setup and configures the winsock2.DLL
'        create() - Creates the socket for both TX and RX
'           bindit() - setup our created socket to make it a listening port
'           sendit() - Sends a packet of data via the TX socket
'           recvit() - Receives a packet of data (if available) from the RX port
'     closedown() - shuts down the winsock2.DLL and free-up program memory spaces
'
' PRE-RUNNING HINTS:
' Before you can run this program in IBPro, you will have to create an import library for the ws2_32.dll
' This can be found in the IDE menu under 'Tools', select 'create import library', find the ws2_32.dll
' file on your system, select it, and click on the open button - simple! :)
' INSTRUCTIONS:
' When you run this program, a dialog window will appear. This window asks you to enter the IP address
' and/or Port number of the remote computer to communicate with. By default, the parameters are set for
' the loopback address 127.0.0.1 and port 20000 respectively - so the demo can run without the need for
' a second computer.
' If you install this program on two machines, be sure to have the IP address of the remote computer
' entered in the Configuration dialog window. Leave the socket number as is, unless another application
' is using it (possible, but unlikely).
' Once this is done, a standard window will open up, starting the network demo. You exit the program by
' merely closing the demo window.
' If the program encounters a network error, the program exits immediately and an error box will appear.
'
'
' If you have any questions/suggestions/whatever, please feel free to comment.
'
'
' Enjoy! 
'
' Valentin



REM define a window variable
DEF w1:WINDOW
DEF d1:DIALOG
DEF setaddress:STRING
DEF setport:INT
DEF result:INT
'DEF myicon:int
'define the dialog and two controls

'********* Declare the underlying winsock2 DLL functions here ***********

$USE "ws2_32.lib"

DECLARE IMPORT,ioctlsocket(s:uint,cmd:int,argp:pointer),int
DECLARE IMPORT,WSAGetLastError(),int
DECLARE IMPORT,WSAStartup(wVR :int, lpWSAD:MEMORY),int
DECLARE IMPORT,WSACleanup(),int
DECLARE IMPORT,socket(af:int,s_type:int,protocol:int),int
DECLARE IMPORT,bind(s:uint, addr:pointer, namelen:INT),INT
DECLARE IMPORT,htons(hostshort:int),int
DECLARE IMPORT,htonl(hostlong:int),INT
DECLARE IMPORT,inet_addr(cp:String),int
DECLARE IMPORT,connect(s:uint, addr:INT, namelen:INT),int
DECLARE IMPORT,listen(s:uint, backlog:INT),INT
DECLARE IMPORT,send(s:uint,buf:string,buflen:int,flags:int),int
Declare IMPORT,recv(s:uint,buf:string,buflen:int,flags:int),int
Declare IMPORT,sendto(s:uint,buf:string,buflen:int,flags:int,addr:pointer, namelen:int),int
Declare IMPORT,recvfrom(s:uint,buf:string,buflen:int,flags:int,addr:pointer, namelen2:int),int
DECLARE IMPORT,accept(s:uint, addr:int, addrlen:INT),INT
DECLARE IMPORT,shutdown(s:uint, how:INT),INT
Declare IMPORT,closesocket(s:uint),INT
Declare IMPORT,gethostname(hostname:string, namelen :int),int
Declare IMPORT,gethostbyname(hostname:string),int
Declare IMPORT,inet_ntoa(inn :int),int

'********* Define Winsock2 data structures here ***********

TYPE WSADataType
   DEF wVersion:WORD 
   DEF wHighVersion:WORD 
   DEF strDescription[257]:ISTRING 
   DEF strSystemStatus[129]:ISTRING 
   DEF iMaxSockets:INT 
   DEF iMaxUdpDg:INT 
   DEF lpVendorInfo:POINTER 
ENDTYPE


   def StartupData:WSADataType

TYPE sockaddr_local
   DEF   sin_family : word
   DEF   sin_port : word
   DEF   sin_addr : int
   DEF   sin_zero[8] : ISTRING
ENDTYPE

   def StructServer:sockaddr_local


Type HostEnt
    DEF h_name :POINTER
    DEF h_aliases :POINTER
    DEF h_addrtype:WORD
    DEF h_length:WORD
    DEF addrlist :POINTER
EndType

   DEF StructHostEnt:HostEnt

TYPE sockaddr_remote
   DEF   sin_family:word
   DEF   sin_port:word
   DEF   sin_addr:int
   DEF   sin_zero[8]:ISTRING
ENDTYPE

   DEF StructClient:sockaddr_remote

'********* Declare system variables and constants here ***********

   DEF tempsd,mHost:MEMORY
   ALLOCMEM tempsd,1,len(StartupData)
   
   setid "NOBLOCK", 1
   setid "FIONBIO" , 0x8004667E
   setid "WSVER2",         0x202
   setid "NO_ERROR",      0
   setid "AF_INET",      2
   setid "SOCK_STREAM",   1
   setid "SOCK_DGRAM",    2
   setid "IPPROTO_UDP",   17
   setid "IPPROTO_TCP",   6
   setid "INVALID_SOCKET",   1
   setid "SOCKET_ERROR",   1
   setid "INADDR_ANY",      0
   setid "MaxConnections",   1
   def tino:int
   def xpos,ypos,zpos:float
   DEF iResult,addrlen,s_socket,c_socket,AcceptSocket,ListenOut,noblock,Ready,WinSock,LenStructClient,host,addr,perror,vv:int
   DEF bufor:string
   DEF WelcomeMessage,localname,MyIP,flightdata:string
   def AddrPointer:pointer
   def noblocking:pointer

       
      AddrPointer = addr


CREATEDIALOG d1,0,0,223,199,0x80C80080,0,"Caption",&dialoghandler
CONTROL d1,@EDIT,"127.0.0.1",51,33,106,26,0x50800000,1
CONTROL d1,@EDIT,"20000",51,88,107,27,0x50800000,2
CONTROL d1,@BUTTON,"CONNECT",60,150,92,22,0x50000000,3
CONTROL d1,@STATIC,"I.P. Address",67,9,74,20,0x5000010B,4
CONTROL d1,@STATIC,"Port Number",65,66,81,20,0x5000010B,5

result = DOMODAL d1


'open the window
WAITUNTIL d1 = 0
closedialog d1,@IDOK
openwindow w1,0,0,800,300,@SIZE|@MINBOX|@MAXBOX|@NOAUTODRAW,0,"PC-2-PC Version 3.0",&mainwindow
'start system tmer and run main program loop until main window is closed
starttimer w1,1000
WAITUNTIL w1 = 0
IF perror<>0
'Put simple messagebox indicating any network errors (if any)
IF MESSAGEBOX(w1,"Network Error","error",@MB_OK) = @IDRETRY
ENDIF
ENDIF

'Call network shutdown routine
closedown()
'All done!
END


'********* the message handler subroutine for the network config window **********

sub dialoghandler
select @MESSAGE
case @IDCONTROL
select @CONTROLID
case 3
                setaddress = GETCONTROLTEXT(d1, 1)
                setport = VAL(GETCONTROLTEXT(d1, 2))
closedialog d1,@IDOK
endselect
case @IDINITDIALOG
CENTERWINDOW d1
endselect
return
endsub



'********** Main Program Loop begins here ***********

sub mainwindow:
    IF @CLASS = @IDCLOSEWINDOW
        CLOSEWINDOW w1
    ENDIF
    IF @CLASS = @IDTIMER
vv=vv+1
if vv = 1
startup()
endif
if vv = 2
create()
endif
if vv = 3
bindit()
endif
if vv > 4
sendit()
endif
if vv > 5
recvit()
endif       
    ENDIF
RETURN
ENDSUB

'********* Initialise Winsock2 DLL here **********

sub startup:
   print w1,"* Start Winsock2"
   iResult=WSAStartup( @WSVER2 , tempsd)
   if iResult<>@NO_ERROR
   print w1,"WSAStartup ERROR"
   CLOSEWINDOW w1
   endif
return
ENDSUB

'********** Create TX and RX sockets here ************

sub create:
'CREATE TRANSMIT SOCKET
    print w1,"* Make Tx socket"
   c_socket=socket(@AF_INET, @SOCK_DGRAM,@IPPROTO_UDP )
   if c_socket=@INVALID_SOCKET
     print w1,"INVALID SOCKET"
     CLOSEWINDOW w1
endif
'CREATE RECEIVE SOCKET
   print w1,"* Make Rx socket "
   s_socket=socket(@AF_INET, @SOCK_DGRAM,@IPPROTO_UDP )
   if s_socket=@INVALID_SOCKET
   print w1,"INVALID SOCKET"
   CLOSEWINDOW w1
   endif
return
ENDSUB


'********** bind and configure the RX socket here ************

sub bindit:
'BIND THE RECEIVING SOCKET AND MAKE IT A LISTENING PORT!
   Structserver.sin_family = @AF_INET
   Structserver.sin_addr = htonl(@INADDR_ANY)
   Structserver.sin_port = htons(setport)

   Structclient.sin_family = @AF_INET
   Structclient.sin_addr = inet_addr( setaddress )
   Structclient.sin_port = htons(setport)


   print w1,"* Binding sockets"
   perror = bind(s_socket,StructServer,len(StructServer))
   print s_socket
   if perror<>@NO_ERROR
   print w1,"INVALID SOCKET"
   CLOSEWINDOW w1
   endif
move w1,40,150
    print w1,"diagnostic purposes only:"
    noblock=1
    noblocking=noblock
    perror = ioctlsocket(s_socket,@FIONBIO, noblocking)
move w1,40,170
print w1,"server socket setup error =",perror
    perror = ioctlsocket(c_socket,@FIONBIO, noblocking)
move w1,40,190
print w1,"client socket setup error =",perror
    perror = WSAGetLastError()
move w1,40,210
print w1,"General setup error =",perror
return
ENDSUB


'******** Data packet TX handled here **********

sub sendit:
    xpos=22/7
    ypos=23/7
    zpos=zpos+1
    flightdata="'This is UDP Data Packet no."+STR$(zpos)+"'"
    perror=sendto(c_socket,flightdata,len(flightdata),0,Structclient,len(Structclient))
move w1,40,80
print "packet data length =",perror,"Bytes"
    move w1,40,40
print w1,"local message =",flightdata
   if perror=@INVALID_SOCKET
   print w1,"INVALID SOCKET"
   CLOSEWINDOW w1
   endif
return
ENDSUB


'******* Data packet RX handled here ********

sub recvit:

perror = recvfrom(s_socket, bufor,2048, 0,0,0)
perror = WSAGetLastError()
move w1,40,60
    print w1,"remote message =",bufor
move w1,300,80
print w1,"Last network error =",perror,"          "
return
ENDSUB

' ******** closedown routine handled here **********


sub closedown:   
   closesocket(s_socket)
   closesocket(c_socket)
   WSACleanup()
   freemem tempsd
   freemem mHost
return
endsub


Ionic Wind Support Team

basman74

May 31, 2009, 09:50:14 AM #1 Last Edit: May 31, 2009, 09:55:52 AM by basman74
Hi Paul,

Greetings from Oz! It's been a while :)

Thankyou for digging up my first attempt at windows API coding! Lost my source copy when the 'ol Win98 desktop HD crashed (bigtime), along with an unreadable CD backup(!).

IIRC, that was the only API snippet submitted by me back on the Pyxia forums, but not my last attempt at coding by any means. Will have to look at digging the others up later (those that didn't meet the same fate as the UDP networking code that is ;D).


Regards,

Valentin Angelovski

PS: I still use IBasic/EBasic for the odd short application every now and then - awesome stuff - keep up the good work!