Tutorial 07: How to do Sockets

May 01, 2008

© NSB Corporation. All rights reserved.

Contributed by Marcio Annunciato


Introduction

It's fairly simple to include networking functionality in your NS Basic application. This tutorial will guide you with a simple example, so even a beginner should have no problem.

 

How is it done?

Including network support in your application starts as simply as adding a library to your project. TcpIpLib is included with NS BASIC. Add it to your project as a resource using Project...Add Resource and use the LoadLibrary call to initialize it in your program.

Once you do that, you have some extra methods to play with:

(For a complete reference on the methods above, make sure you read the chapter 1 of Tech Note 18)

If you ever worked with TCP or even saving/reading files from the file system the methods above should mean something for you. If you didn't, don't worry, it's not difficult to understand. You talk to other computers in a similar way you deal with files:

Because you are dealing with a remote system and not a local file, you have a "timeout" feature. It simply means that if your application does not hear from the remote machine for a specified period of time it will give up.

You must also specify to which service you want to connect in that remote machine, and that's the concept behind "port". Different ports provides different services, for instance,

 

Let's check our Email server!

In this project will simply connect to a pop3 server, send username and password, and display the result to the STAT command (it should tell how many messages you have). Let's now put a button and a multi-line field on a form, and the code in the button, as the picture below:

Now let's analyze the code, step by step:

This is what is called a chat-style connection. You send something and wait for a response. Thats how the POP3 server works:

You can tell if the reponse is a success or an error on POP3 protocol by looking at the first character of the response line: a plus means it was accepted, a minus means there was a problem.

Of course this is a very simple example to get you started. A real application would have functions to get lines and to send lines, and also check if the password was accepted, parse the STAT result lines to display only the number of messages and not the entire ugly line, and even retrieve the header of each message and display the sender, subject and date of all the emails, and much more. Make sure to check the TcpIpDemo project on the samples folder of your NS BASIC installation, there you will find the functions I am talking about as well as an example to send email, and to retrieve a web page.

Here is how it would look like after you compile and run our sample:

 

References: