Program Examples:TCP IP:TCPIP TelNet Server
The following example demonstrates the set up of a TelNet TCP-IP server.
The server opens a socket and blocks on "Accept" until a telnet session gets connected. A 'How To Use' guide is sent to the telnet explaining the basic functionality on the client side.
common shared Running_TCP_Server as long = 1
common shared x as long = 0
common shared y as long = 0
program 'continue
dim main_str as string
dim chr_str as string
dim i as long = 0
dim tokens[64] as string
dim num_of_tokens as long
Try
OpenSocket Options=1 as #1
catch 5043 'socket is already open
print "socket 1 is already open. Closing and reopening"
close #1
OpenSocket Options=1 as #1
End Try
main_str = "Welcome to TelNet TCP/IP Server"
Accept(#1, 6001)
print #1,main_str
print #1,"recognizes 2 variables x and y"
print #1,"Set variable"
print #1,"x value <enter>"
print #1,"y value <enter>"
print #1,"read variable"
print #1,"x <enter>"
print #1,"y <enter>"
main_str = ""
while Running_TCP_Server
if loc(1) = 0 then ' if no characters are waiting to be read
sleep 10
else
chr_str = input$(1,#1) ' receive one byte
print chr_str ' DEBUG
main_str = main_str + chr_str
if asc(chr_str) = 0xA then ' Line Feed - The client clicked return
print main_str ' DEBUG
num_of_tokens = TokenizeStr(main_str,tokens)
call ParseStr(main_str,tokens,num_of_tokens)
main_str = ""
end if
sleep 10
end if
end while
main_str = "Closing TelNet TCP/IP Server"
print #1,main_str; 'send
close #1
Print "Server Closed Sockets. Server Exits"
end program
Sub ParseStr(str_to_parse as string, tokens[*] as string,byval num_of_tokens as long)
select case tokens[1]
case "x"
if (1 = num_of_tokens ) then
print #1, x
else
x = val(tokens[2])
end if
case "y"
if (1 = num_of_tokens ) then
print #1, y
else
y = val(tokens[2])
end if
case "quit"
Running_TCP_Server = 0
case else
print #1, "Error"
end select
end sub
function TokenizeStr(byval str_to_tokenize as string, tokens[*] as string) as long
dim space_index as long = 1
TokenizeStr = 1
while space_index <> 0
space_index = instr(str_to_tokenize, " ")
if space_index <> 0 then
tokens[TokenizeStr] = left$(str_to_tokenize, space_index - 1)
str_to_tokenize = right$(str_to_tokenize, len(str_to_tokenize) - space_index)
TokenizeStr = TokenizeStr + 1
end if
end while
tokens[TokenizeStr] = left$(str_to_tokenize, len(str_to_tokenize) - 2)
end function