Video tutorial here!
#TCP Server This brings us to today’s objective, which is implementing perhaps the simplest server of them all: a TCP server. We’ll write a simple script Dart that:
- Listens on a port for incoming connections
- Prints incoming messages to the screen
So, let’s get started.
#Setup For this tutorial, you will need to install the Dart SDK.
I also recommend using JetBrains WebStorm as your IDE, but that’s not a requirement. You can write your code in even Notepad.
Visual Studio Code and Brackets are also quite good.
Now that we have our editor of choice, we need to set up our package structure.
bin/ directory will hold our “executable” script.
#The Code So, let’s get started.
##Listening on a Port
Create a new
main.dart file within
Add the following code.
What did we just do?
importcall exposes code for us to use within our script.
dart:asyncallows us to perform asynchronous actions, and
dart:ioallows us to work with sockets and I/O.
- We bound a socket to port 3406. This socket will listen for incoming connections.
- Our socket was implemented as a
##Server Socket Callback
Now, in your
main function, just after your call to
ServerSocket.bind, add this code:
- Once our socket is bound to localhost:3406, we
can run a callback on it that accepts a
ServerSocketas a parameter.
- We tell our server to listen for incoming connections,
and then handle them with a callback called
handleIncoming, which we are about to write.
##Handling Incoming Connections
Now, add the following code to your file:
- Our socket listens for incoming data.
- When this data is received, you can run a callback
that accepts a List
. Each of these ints represents a byte.
- Now, we just have to convert the bytes to a string, and print to the console.
#Testing Now, we’ve written our functional TCP server. We just need to see it in action.
To start our server, simply:
Windows users can look into PacketSender for a GUI-based TCP client.
On Unix-based systems, you can use netcat to easily connect to our server through TCP.
Our server will print
Hello Dart to the screen!
#What we’ve Done Good job! You’ve written a Dart server that:
- Listens on a TCP port
- Receives incoming connections
- Prints messages to the console
Stay tuned for more tutorials!
Here is a link to the video version of this tutorial.
Follow me on Twitter: http://twitter.com/thosakwe