UDT Tutorial

### Hello World!

In this section we will introduce the simplest UDT program that can transfer data in high performance.

This simple "Hello World!" example includes a server program and a client program just like any socket programming tutorial. These are the simpler version of the appserver and appclient examples in ./app directory.

To compile, use gcc -o server server.cpp -I <udt.h location> -L <libudt.so location> -ludt -lstdc++ -lpthread. For more details, please refer to the Makefile in ./app directory.

UDT server example

#include <arpa/inet.h>
#include <udt.h>
#include <iostream.h>
using namespace std;
int main()
{
UDTSOCKET serv = UDT::socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in my_addr;
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(9000);
my_addr.sin_addr.s_addr = INADDR_ANY;
memset(&(my_addr.sin_zero), '\0', 8);
if (UDT::ERROR == UDT::bind(serv, (sockaddr*)&my_addr, sizeof(my_addr)))
{
cout << "bind: " << UDT::getlasterror().getErrorMessage();
return 0;
}
UDT::listen(serv, 10);
int namelen;
sockaddr_in their_addr;
UDTSOCKET recver = UDT::accept(serv, (sockaddr*)&their_addr, &namelen);
char ip[16];
cout << "new connection: " << inet_ntoa(their_addr.sin_addr) << ":" << ntohs(their_addr.sin_port) << endl;
char data[100];
if (UDT::ERROR == UDT::recv(recver, data, 100, 0))
{
cout << "recv:" << UDT::getlasterror().getErrorMessage() << endl;
return 0;
}
cout << data << endl;
UDT::close(recver);
UDT::close(serv);
return 1;
}

This simple server tries to bind itself at port 9000. If succeed, it listens at port 9000 and accepts a client and then reads a string.

UDT client example

#include <iostream>
#include <udt.h>
#include <arpa/inet.h>
using namespace std;
using namespace UDT;
int main()
{
UDTSOCKET client = UDT::socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in serv_addr;
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(9000);
inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr);
memset(&(serv_addr.sin_zero), '\0', 8);
// connect to the server, implict bind
if (UDT::ERROR == UDT::connect(client, (sockaddr*)&serv_addr, sizeof(serv_addr)))
{
cout << "connect: " << UDT::getlasterror().getErrorMessage();
return 0;
}
char* hello = "hello world!\n";
if (UDT::ERROR == UDT::send(client, hello, strlen(hello) + 1, 0))
{
cout << "send: " << UDT::getlasterror().getErrorMessage();
return 0;
}
UDT::close(client);
return 1;
}

The client side connects to the local address (127.0.0.1) at port 9000, and sends a "hello world!" message.

Note that in this "Hello World!" example the UDT::send and UDT::recv routines should use a loop to check return value. However, since the string length is very small and can be hold in one packet, we omit the loop part in order to give a simpler example.