Basic TCP Server

From Nutwiki
Revision as of 12:58, 12 April 2011 by Niziak (Talk)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

First register network driver and configure interface by using DHCP.

<source lang="c"> NutRegisterDevice(&DEV_ETHER, 0, 0); if (NutDhcpIfConfig(DEV_ETHER_NAME, 0, 60000)) {

   /* Error: Cannot configure interface. */

} </source>

There are several alternatives:

Next, create a socket and wait for client connections at a specified port (8000).

<source lang="c"> sock = NutTcpCreateSocket(); if (NutTcpAccept(sock, 8000)) {

   /* Error: Cannot connect server. */

} </source>

To prevent DOS attack, set timeout value for established TCP connection:

<source lang="c"> uint32_t to = 10000; NutTcpSetSockOpt(sock, SO_RCVTIMEO, &to, sizeof(to)); </source> You may then receive data from the client...

<source lang="c"> got = NutTcpRecv(sock, buffer, len); if (got <= 0) {

   /* Error or connection closed by the client. */

} </source>

... or send data to the client.

<source lang="c"> if (NutTcpSend(sock, buffer, len) != len) {

   /* Error or connection closed by the client. */

} </source>

When done, close the socket. This will also close the connection if it is still established.

<source lang="c"> NutTcpCloseSocket(sock); </source>

For more advanced applications you can redirect the connected socket to a file stream and use standard I/O functions like fprintf() or fscanf() for sending and receiving data.

<source lang="c"> FILE *stream; /* ... more code here ... */

stream = _fdopen((int) sock, "r+b"); /* ... more code here ... */

/* Sending data. */ fprintf(stream, "Welcome!\r\n"); /* ... more code here ... */

/* Receiving data. */ got = fread(buffer, 1, len, stream); /* ... more code here ... */ </source>

Do not forget to close the stream with fclose() and socket with NutTcpCloseSocket().

See also