You are viewing an older revision! See the latest version

Socket

Table of Contents

  1. TCP Socket
  2. UDP Socket

The mbed C++ Socket API is a simple abstraction on top of the Berkeley sockets API.

The Socket library is included within the Networking libraries (Ethernet Interface and VodafoneK3770 Interface).

TCP Socket

TCP Echo Server:

Import program

00001 #include "mbed.h"
00002 #include "EthernetInterface.h"
00003 
00004 int main (void) {
00005     EthernetInterface eth;
00006     eth.init(); //Use DHCP
00007     eth.connect();
00008     printf("IP Address is %s\n", eth.getIPAddress());
00009     
00010     TCPSocketServer server;
00011     server.bind(7);
00012     server.listen(1);
00013     
00014     while (true) {
00015         printf("\nWait for new connection...\n");
00016         TCPSocketConnection client;
00017         server.accept(client);
00018         
00019         printf("Connection from: %s\n", client.get_address());
00020         char buffer[256];
00021         while (true) {
00022             int n = client.receive(buffer, 256, 3000);
00023             if (n <= 0) break;
00024             
00025             client.send_all(buffer, n, 3000);
00026             if (n <= 0) break;
00027         }
00028         client.close();
00029     }
00030 }

UDP Socket

#include "UDPSocket.h"

Import library

Public Member Functions

UDPSocket ()
Instantiate a UDP Socket.
int bind (int port)
Bind a socket to a specific port.
int sendTo (char *data, int length, char *host, int port, int timeout=0)
Send data to a remote host.
int receiveFrom (char *data, int length, char **host, int *port, int timeout=0)
Receive data from a remote host.
int close ()
Close the socket.

All wikipages