Blitz2D Intermediates: TCP Using BlitzBasic Stream Commands
by Semar

Overview:

The new tcp commands added in Blitz since the 1.52 version allow to make powerful client/server application working on a network and in internet.

The core behind that new tcp commands, is the "stream" concept: a stream acts like a network channel where read data from and write data to.

The program that opens a port for listening, is a "server" program; the program that connects to that port, using a stream channel, is a "client" program.

How it Works

The server program opens a port, and stay listening for a client connection.

Then a client attempts to create a stream channel between itself, and the server port. If the connection is successfully estabilished, then a stream is opened and the client and the server communicates through that stream.

When another client attempts to connect to the server, it also will attempt to create a new stream channel between itself and the server's opened port. If the connection is estabilished, a new stream is opened between the server and the new client.

So, the port used is always the same - the one that the server has opened; while the stream channels are different, one for each client connected.

To connect to the server's port, the client should know the number of the port, and the network/internet address of the machine where that port is opened; while the server does not need any other info about the client, but the client's stream ID.

But, how the server knows the client's ID in order to communicate with it ? Let's answer to this question in the next section.

A Bit of Code

Let's create now a server that stay listening on a certain port. The code would be similar to this:


This command will attempt to open a port on the pc where the program is running. The command will return a number which is:
0 - failed to create a port
n - a positive number greater than 0, that represents the handler of the port

In this case, the variable svrGame will represent the port's handler. If svrGame is = 0, then the port was not opened; otherwise, svrGame will be a positive number.


Now we should listen for a first client connection; the command to check if there's a new connection is: strStream=AcceptTCPStream(svrGame)

where:
strStream is the handler of the successful stream that was opened between the client and the server.
svrGame is the handler of the server's opened port

The function reports 0 if there is no new connection, otherwise reports the stream handler assigned to the client just connected.


To get the fully commented source for this article: Click Here


For a printable copy of this article, please click HERE.


This site is Copyright© 2000-2004, BlitzCoder. All rights reserved.