You are viewing an older revision! See the latest version

Socket

Table of Contents

  1. TCP Socket
  2. UDP Socket

Network Interfaces

  1. Socket API
  2. Ethernet Interface
  3. VodafoneK3770 Interface

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

/media/uploads/emilmont/sockets.png

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 }

You can test the above server running on your mbed, with the following Python script running on your PC:

import socket

ECHO_SERVER_ADDRESS = "10.2.131.195"
ECHO_PORT = 7

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
s.connect((ECHO_SERVER_ADDRESS, ECHO_PORT))

s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

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