+ All Categories
Home > Documents > 4 Sockets 4.1 Sockets using C - hs-fulda.degross/lecture_parallel/chap4.pdf · bind a well-known...

4 Sockets 4.1 Sockets using C - hs-fulda.degross/lecture_parallel/chap4.pdf · bind a well-known...

Date post: 06-Mar-2018
Category:
Upload: ngothien
View: 216 times
Download: 3 times
Share this document with a friend
22
Parallel Programming Slide 4 - 1 Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß 4 Sockets 4.1 Sockets using C sockets are available since 1982 with BSD-UNIX 4.1c for VAX com- puters from the former Digital Equipment (then Compaq and now HP) the interface has been revised many times in the past Application Programming Interface (API) for connection-oriented data transmission (TCP/IP) create a socket bind a well-known port number to the socket establish a queue for connections accept a connection read from connection write to connection close a connection Server Client socket () bind () listen () accept () connect () recv () recvfrom () recvmsg () send () sendto () sendmsg () recv () recvfrom () recvmsg () send () sendto () sendmsg () socket () close () close () ... ... establishing connection data transfer (a connection will be established if the client connects to the port where the server listens)
Transcript

Parallel Programming Slide 4 - 1

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

4 Sockets

4.1 Sockets using C

• sockets are available since 1982 with BSD-UNIX 4.1c for VAX com-

puters from the former Digital Equipment (then Compaq and now HP)

• the interface has been revised many times in the past

• Application Programming Interface (API) for connection-oriented

data transmission (TCP/IP)

create a socket bind a well-known port number to the socket establish a queue for connections

accept a connection

read from connection

write to connection

close a connection

Server Client

socket ()

bind ()

listen ()

accept () connect ()

recv ()recvfrom ()recvmsg ()

send ()sendto ()sendmsg ()

recv ()recvfrom ()recvmsg ()

send ()sendto ()sendmsg ()

socket ()

close () close ()

... ...

establishingconnection

datatransfer

(a connection will be established if the client connects to the port where the server listens)

Parallel Programming Slide 4 - 2

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• API for connectionless data transmission (UDP/IP)

Server Client

socket ()

sendto ()sendmsg ()

recvfrom ()recvmsg ()

sendto ()sendmsg ()

socket ()

close () close ()

... ...data transfer(datagrams)

bind ()

recvfrom ()recvmsg ()

• some necessary data structures

struct sockaddr /* common socket address */ { /* (e.g. for function calls) */ u_short sa_family; /* address fami ly: AF_xxx value */ char sa_data[14]; /* up to 14 byt es of protocol */ }; /* specific a ddress */

struct in_addr /* internet address */ { u_long s_addr; /* network byte ordered netid/hostid */ };

if INADDR_ANY will be assigned to s_addr the socket will accept connections from any of the network interfaces on this computer (usually a computer has only one interface if it isn't a gateway)

struct sockaddr_in /* internet style socket address */ { short sin_family; /* AF_INET */ u_short sin_port; /* network byte ordered port number */ struct in_addr sin_addr; /* network byte ordered netid/hostid */ char sin_zero[8]; /* unused (padd ing to 14 bytes) */ };

Parallel Programming Slide 4 - 3

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• some functions of the socket API

− create an endpoint for communication

int socket (int family, int type, int protocol); family: AF_INET ...

type SOCK_STREAM SOCK_DGRAM ...

protocol generally 0 (May be unequal zero if you use an arbitrary protocol, e.g. ICMP, with

so called raw sockets (SOCK_RAW). Raw sockets need superuser (administrator, root, ...) privileges.)

♦ the arguments specify the address family and socket type

♦ the function returns a socket descriptor

− bind an address (name) to an unnamed socket

int bind (int sockfd, struct sockaddr *myaddr, int addrlen); sockfd socket descriptor

myaddr protocol specific address (e.g., struct sockaddr_in)

addrlen size of address structure

♦ our name myaddr consists of an IP address and port number

Parallel Programming Slide 4 - 4

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

− establish a queue for connections

int listen (int sockfd, int backlog); sockfd socket descriptor

backlog defines the maximum length the queue of pending connections may grow to (some implementations allow only a maximum value of 5)

♦ signals that the server is ready to accept connections

♦ queue is necessary because the server may be busy

(blocking server: talking to an existing client, ... non-blocking server: creating a child process to handle a request, ...)

♦ attempts to connect will be refused if the limit on pending

connections has been reached

− accept a connection

int accept (int sockfd, struct sockaddr *addr, int *addrlen); sockfd socket descriptor

addr result parameter that is filled in with the address of the connecting client

addrlen initially, it contains the amount of space pointed to by addr and on return the size of the returned address

♦ extracts first connection of the queue of pending connections ♦ creates a new socket with the properties of sockfd ♦ returns the descriptor for the accepted socket

Parallel Programming Slide 4 - 5

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

− connect to a server port

int connect (int sockfd, struct sockaddr *servaddr, int addrlen); sockfd socket descriptor servaddr protocol specific address addrlen size of address structure

♦ tries to make a connection to another socket

♦ communication parameters like buffer sizes must be co-

ordinated between client and server

− read from / write to connection

int recv (int sockfd, char *buffer, int nbytes, int flags); int recvfrom (int sockfd, char *buffer, int nbytes, int flags, struct sockaddr *from, int *fromlen); int send (int sockfd, const char *buffer, int nbytes, int flags); int sendto (int sockfd, const char *buffer, int nbytes, int flags, const struct sockaddr *to, int tolen);

sockfd socket descriptor buffer pointer to receive / send buffer nbytes size of receive buffer / number of bytes to send

Parallel Programming Slide 4 - 6

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

flags generally 0

from / to protocol specific address (if from is not a NULL pointer, the source address of the message is

filled in)

fromlen initially, it contains the amount of space pointed to by

from and on return the size of the returned address

tolen size of address structure

♦ send () / recv () need a connection-oriented protocol

♦ sendto () / recvfrom () can be used with connection-oriented

and connectionless protocols

♦ all functions return the number of bytes received / sent

• converting byte orders

u_short htons (u_short hostshort); /* byte o rder: host -> network */ u_long htonl (u_long hostlong); u_short ntohs (u_short netshort); /* byte o rder: network -> host */ u_long ntohl (u_long netlong);

• address conversion

unsigned long inet_addr (char *); /* IP-ad dress -> internal */ char *inet_ntoa (struct in_addr); /* inter nal -> IP-address */

Parallel Programming Slide 4 - 7

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• example: common macros for echo server / client (tcp_cliserv.h)

... #ifndef PARSERV #define PARSERV 1 /* 0: block ing server */ #endif /* 1: paral lel server */ #define DEFIPADDR "127.0.0.1" /* default IP address */ #define DEFPORT 8888 /* default port */ #define BUFLEN 80 /* buffer s ize */ #define ADDRLEN 16 /* IP Addr. length (+1 for \0) */ #define MAXQUE 3 /* max. # o f waiting processes */ /* operating system dependent type (special problem with Linux and * Solaris x86 because the type depends on the rele ase: "socklen_t" * isn't defined in older versions) * * Linux up to 2.0.x and Solaris x86 up to 2.5.1: * #if defined(SunOS) && defined(sparc) * remark: results in warnings on newer systems but is nevertheless the * "secure" way for old and new systems * * starting with Linux 2.2.x and Solaris x86 2.7: * #if defined(SunOS) || defined(Linux) * remark: results in errors on older systems */ #if defined(SunOS) || defined(Linux) || defined(Cyg win) || defined(Darwin) #define SOCKLEN_T socklen_t * #else #define SOCKLEN_T int * #endif /* operating system dependent function */ #ifdef Win32 #ifndef WIN32 #define WIN32 #endif #define CLOSE closesocket #else #define CLOSE close #endif #ifdef Win32 #define WMAJOR 2 /* WinSocke t version */ #define WMINOR 2 #undef PARSERV /* only the blocking server */ #define PARSERV 0 /* has be en implemented */ #endif /* return values ("exval") for macro "TestMinusOne" */ #define ESOCK -1 /* error ca lling "socket ()" */ ... /* evaluate the return value of a function */ #define TestMinusOne(val,line,function,exval) \ if (val == -1) { fprintf (stderr, "line %d: \"%s ()\" failed: %s\n", \ line, function, strerror (errno) ); exit (exval); } #define TestNotZero(val,line,function) \ if (val != 0) { fprintf (stderr, "line %d: \"%s ( )\" failed: %s\n", \ line, function, strerror (val)); exit (E XIT_FAILURE); }

Parallel Programming Slide 4 - 8

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• example: connection-oriented echo-server

− the macro TestMinusOne has been left out for shortness

− the non-blocking server creates concurrent processes

... #include "tcp_cliserv.h" #if defined(Linux) || defined(SunOS) || defined(Cyg win) || ... #include <sys/socket.h> ... #endif #ifdef Win32 #include <winsock2.h> #include <process.h> #endif

int listenfd; /* listen() socket descriptor */

/* signal handler for <Ctrl-c> or <Strg-c> resp. to close "listenfd" */ void MySigInt (int sig);

int main (int argc, char *argv[]) { int connfd, /* connect( ) socket descriptor */ clilen, /* address length */ ... unsigned short serv_port; /* server p ort */ struct sockaddr_in cli_addr, /* client/s erver address */ serv_addr; #if PARSERV == 1 int finish; /* terminat e connection server */ pid_t childpid; /* process ID */ #endif #ifdef Win32 WORD WinSockVers; /* socket v ersion */ WSADATA wsaData; /* for WinS ockets */ #endif ...

#ifdef Win32 WinSockVers = MAKEWORD (WMAJOR, WMINOR); ret = WSAStartup (WinSockVers, &wsaData); if (ret != 0) { fprintf (stderr, "line: %d: \"WSAStartup ()\" failed: Couldn't " "find library.\n", __LINE__); exit (EWINSOCK); } if ((LOBYTE (wsaData.wVersion) != WMAJOR) || (HIBYTE (wsaData.wVersion) != WMINOR)) { fprintf (stderr, "line: %d: Library doesn't s upport " "WinSock %d.%d\n", __LINE__, WMAJOR, WMINOR); WSACleanup (); exit (EWINSOCK); } #endif ... /* open socket */ listenfd = socket (AF_INET, SOCK_STREAM, 0); /* install signal handler */ ... memset ((char *) buffer, 0, sizeof (buffer));

Parallel Programming Slide 4 - 9

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

memset ((char *) &serv_addr, 0, sizeof (serv_addr )); /* bind port to socket and wait for connections */ serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl (INADDR_ANY); serv_addr.sin_port = htons (serv_port); ret = bind (listenfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)); printf ("TCP server is ready and waiting for conn ections ...); ret = listen (listenfd, MAXQUE); #if PARSERV == 1 finish = 0; while (finish == 0) { clilen = sizeof (cli_addr); connfd = accept (listenfd, (struct sockaddr *) &cli_addr, (SOCKLEN_T) &clilen); childpid = fork(); switch (childpid) { ... case 0: /* child pr ocess */ { ... ret = CLOSE (listenfd); ... printf ("New server process for client request ...); more_to_do = 1; while (more_to_do == 1) { len = recv (connfd, buffer, BUFLEN, 0); ... for (i = 0; i < len; ++i) { buffer[i] = (char) toupper ((int) b uffer[i]); } if (send (connfd, buffer, len, 0) == -1) { fprintf (stderr, "line %d: failure in ...); } if ((strcmp (buffer, "QUIT\n") == 0) || (strcmp (buffer, "QUIT") == 0)) { ret = CLOSE (connfd); printf ("TCP server %ld: " ...); more_to_do = 0; /* terminat e process */ } memset ((char *) buffer, 0, sizeof (b uffer)); } finish = 1; break; } default: /* parent p rocess */ ret = CLOSE (connfd); /* accept another connection */ } } printf ("TCP server %ld has finished\n", (long) getpid ()); #else ... #endif return EXIT_SUCCESS; } ...

Parallel Programming Slide 4 - 10

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• example: connection-oriented client

... int main (int argc, char *argv[]) { ... /* initialize "serv_addr" */ memset ((char *) &serv_addr, 0, sizeof (serv_addr )); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr (serv_ip_addr); serv_addr.sin_port = htons (serv_port); /* open socket */ connfd = socket (AF_INET, SOCK_STREAM, 0); /* connect to server */ ret = connect (connfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)); printf ("connected to server at %s on port %d\n", serv_ip_addr, serv_port); more_to_do = 1; while (more_to_do == 1) { printf ("string to send (\"quit\" terminates co nnection): "); fgets (buffer, BUFLEN, stdin); ... if (len > 0) { if (send (connfd, buffer, len, 0) == -1) { fprintf (stderr, "line %d: failure in \"sen d ()\": %s\n", __LINE__, strerror (errno)); } if (recv (connfd, buffer, BUFLEN, 0) == -1) { fprintf (stderr, "line %d: failure in \"rec v ()\": %s\n", __LINE__, strerror (errno)); } else { printf ("Received from echo server at %s: % s\n\n", inet_ntoa (serv_addr.sin_addr), buf fer); } if ((strcmp (buffer, "QUIT\n") == 0) || /* terminate process ? */ (strcmp (buffer, "QUIT") == 0)) { more_to_do = 0; /* yes */ } } else { printf (" !!! I can't send an empty string ...); } } ret = CLOSE (connfd); return EXIT_SUCCESS; }

Parallel Programming Slide 4 - 11

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• compiling and linking with Windows 95/98/NT/2000/... (Microsoft C/C++)

cl /W4 /DWin32 sockserv.c /link wsock32.lib cl /W4 /DWin32 sockcli.c /link wsock32.lib

• compiling and linking using UNIX

cc -fd -fast -xtarget=generic -v -Xc [-xc99] -DSunOS sockserv.c -lnsl -lsocket cc -fd -fast -xtarget=generic -v -Xc [-xc99] -DSunOS sockcli.c -lnsl -lsocket

gcc -Wall -Wstrict-prototypes -Wmissing-prototypes -std=c99 -pedantic -DLinux sockserv.c gcc -Wall -Wstrict-prototypes -Wmissing-prototypes -std=c99 -pedantic -DLinux sockcli.c

gcc -Wall -Wstrict-prototypes -Wmissing-prototypes -std=c99 -pedantic -DDarwin sockserv.c gcc -Wall -Wstrict-prototypes -Wmissing-prototypes -std=c99 -pedantic -DDarwin sockcli.c

• the non-blocking server can handle many concurrent clients

simultaneously

• our non-blocking server has a serious flaw (the flaw wouldn't appear if we had used detached threads instead of concurrent processes)

− create and finish some connections − do e.g., a "ps ax | grep sockserv" on a Linux server

196 1 S 0:00 sockserv 210 1 Z 0:00 (sockserv <zombie>) 235 1 Z 0:00 (sockserv <zombie>) 239 1 Z 0:00 (sockserv <zombie>)

⇒ it's impossible to get rid of these zombies without restarting

the server

⇒ the zombies will fill up all process table entries in the kernel

⇒ the server itself must "wait" for its child processes

Parallel Programming Slide 4 - 12

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• preventing zombie processes

− signal SIGCHLD reports a change of the status of a child

⇒ it can be used to "wait" for a child to die

... void sigchld_handler (int sig); /* new signal handler */ ... int main (void) { ... if (signal (SIGCHLD, sigchld_handler) == SIG_ERR) ... } void sigchld_handler (int sig) { while (waitpid ((pid_t) -1, NULL, WNOHANG) > 0) { ; /* pick up childs */ } if (signal (SIGCHLD, sigchld_handler) == SIG_ERR) { perror ("sigchld_handler"); exit (-1); } }

− unfortunately this method has a side-effect: some system calls can

be interrupted if a signal is delivered

⇒ we have to take care of this situation ⇒ e.g., we have to surround such system calls by a while-loop

while ((connfd = accept (...)) < 0) { if (errno != EINTR) { perror ("..."); /* an error has occurred */ exit (...); } }

Parallel Programming Slide 4 - 13

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

4.2 Sockets using Java

• API for connection-oriented data transmission (TCP/IP)

Server Client

ServerSocket ()

close ()

... datatransfer

accept ()

OutputStream ()

InputStream ()

close ()

...

OutputStream ()

InputStream ()

Socket ()establishingconnection

− simplified interface compared to C

− ServerSocket () automatically performs all actions for socket (),

bind (), and listen ()

− Socket () automatically performs all actions for socket () and

connect ()

Parallel Programming Slide 4 - 14

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• public constructors for class ServerSocket

− ServerSocket (int port) throws IOException; (a port of 0 creates a socket on any free port; the port must be between 0 and 65535,

inclusive; the maximum queue length for connect requests is set to 50)

− ServerSocket (int port, int backlog) throws IOException; (the maximum queue length for connect requests is set to backlog)

− ServerSocket (int port, int backlog, InetAddress bindAddr)

throws IOExeception (bindAddr can be used on a multi-homed host for a ServerSocket that will only accept

connect request to one of its addresses; if bindAddr is null it will accept connections on

any / all local addresses)

• some public instance methods for class ServerSocket

Socket accept () accepts a requested connection and

returns a Socket for future communi-

cation between client and server

void close () closes this socket

InetAddress getInetAddress () returns the local address of this

server socket or null

int getLocalPort () returns the port on which this socket

is listening

String toString () returns a string representation of this

socket

Parallel Programming Slide 4 - 15

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• some public constructors for class Socket

− Socket (InetAddress addr, int port) throws IOException; (creates a StreamSocket and connects it to the specified port at the specified IP address)

− Socket (InetAddress addr, int port, InetAddress localAddr, int

localPort) throws IOException; (creates a StreamSocket and connects it to the specified remote port at the specified

remote IP address; the socket will also bind () to the local address and port supplied)

− Socket (String host, int port) throws UnknownHostException,

IOException; (creates a StreamSocket and connects it to the specified port on the named host)

− Socket (String host, int port, InetAddress localAddr, int localPort)

throws IOException;

• some public instance methods for class Socket

void close () closes this socket

InetAddress getInetAddress () returns the remote address to

which the socket is connected

InetAddress getLocalAddress () returns the local address to which

the socket is bound int getPort () returns the remote port number int getLocalPort () returns the local port number

InputStream getInputStream () returns an object that can be used

to read from a socket

Parallel Programming Slide 4 - 16

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

OutputStream getOutputStream () returns an object that can be

used to write to a socket

int getReceiveBufferSize () returns the size of the receive buffer

int getSendBufferSize () returns the size of the send buffer

String toString () a string representation of this socket

• some public class and instance methods for class InetAddress

byte[] getAddress () returns an IP address as an array of

bytes, with the highest-order byte as

the first element of the array

InetAddress getByName (String host) returns the InetAddress of a

host specified by name; if host

equals null the method returns the

address of the local host

String getHostAddress () returns the IP address in the shape of

"%d.%d.%d.%d"

String getHostName () returns the hostname for this address

or null

String toString () converts this IP address to a string

Parallel Programming Slide 4 - 17

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• example: a non-blocking echo-server using threads

Client

Socket

Client

Socket

ServerSocket

Socket

Serverincomingconnection

Thread

Socket

Thread

Socket

Thread

... public class ServerMain { public static void main (String args[]) { final int DEFPORT = 8888; /* default port */ final int MAXQUE = 3; /* max. # o f waiting processes */ int servPort, /* server p ort */ thrID; /* Thread I D */ if (args.length != 1) { servPort = DEFPORT; } else { try { servPort = Integer.parseInt (args[0]); } catch (NumberFormatException e) { ... } } thrID = 0; ... try { /* open socket */ ServerSocket listenfd = new ServerSocket (servPort, MAXQUE); while (true) { /* wait for connection requests */ Socket connfd = listenfd.accept (); (new ConnectionServer (++thrID, connfd)).start (); } } catch (IOException e1) { ... } } }

Parallel Programming Slide 4 - 18

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

class ConnectionServer extends Thread { final int BUFLEN = 80; /* buffer s ize */ private int thrID; /* Thread I D */ private Socket connfd; /* connection socket descriptor */ public ConnectionServer (int thrID, Socket connfd ) { this.thrID = thrID; this.connfd = connfd; setName ("ConnectionServer-" + thrID); } public void run () { byte buffer[] = new byte[BUFLEN];/* request from client */ byte tmp[]; /* temporar y buffer */ boolean noErrors = true; int len; /* # of cha rs in buffer */ String msg = ""; /* received message */ String cli_addr = ""; /* IP addre ss of client */ String name = getName (); try { InputStream in = connfd.getInputStream (); OutputStream out = connfd.getOutputStream (); cli_addr = connfd.getInetAddress ().t oString (); System.out.println (name + ": new connection with " + cli_addr); while ((msg.compareTo ("QUIT\n") != 0) && (msg.compareTo ("QUIT") != 0) && noE rrors) { if ((len = in.read (buffer, 0, BUFLEN)) != -1) { msg = new String (buffer, 0, len); System.out.println (name + ": received: " + msg); msg = msg.toUpperCase (); /* sometimes toUpperCase converts a germa n sharp s to SS */ if ((len = msg.length ()) > BUFLEN) { len = BUFLEN; System.err.println (name + ": buffer to o small. " ...); } /* "buffer" may be too small if the messa ge contains a german * sharp s -> use temporary buffer of app ropriate size */ tmp = msg.getBytes (); out.write (tmp, 0, len); } else { System.out.println (name + ": ...); noErrors = false; } } connfd.close (); System.out.println (name + ": terminated"); } catch (IOException e) { System.err.println (e.toString ()); } } }

Parallel Programming Slide 4 - 19

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• example: the client program

... public class ClientMain { public static void main (String args[]) { final int DEFPORT = 8888; /* default port */ final String DEFIPADDR = "127.0.0.1"; /* default IP address */ final int BUFLEN = 80; /* buffer size */ byte[] buffer = new byte[BUFLEN]; /* reply from server */ String msg = ""; /* keyboard message from user */ String hostAddr; /* name or IP address */ int servPort; /* server p ort */ int len; /* # of cha rs in buffer */

switch (args.length) { case 1: hostAddr = new String (args[0]); servPort = DEFPORT; break; case 2: ... } try { /* open socket */ Socket connfd = new Socket (hostAddr, servPort); InputStream in = connfd.getInputStream (); OutputStream out = connfd.getOutputStream (); BufferedReader con = new BufferedReader ( new InputStreamRead er (System.in)); System.out.println ("connected to server " + ...); while ((msg.compareTo ("QUIT\n") != 0) && (msg.compareTo ("QUIT") != 0)) { System.out.print ("string to send (\"quit\" terminates " ...); msg = con.readLine (); /* keyboard input */ if (msg.length () > 0) { if ((len = msg.length ()) > BUFLEN) { len = BUFLEN; System.err.println ("Input line too lon g. I'll use " ...); } out.write (msg.getBytes (), 0, len); /* send to server */ len = in.read (buffer, 0, BUFLEN); /* reply from server */ msg = new String (buffer, 0, len); System.out.println ("Received from echo s erver " + ...); } else { System.out.println ("Empty input line, i. e. nothing to do."); } } connfd.close (); } catch (IOException e1) { ... } } }

Parallel Programming Slide 4 - 20

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• API for connectionless data transmission (UDP/IP)

Server Client

DatagramPacket ()send ()

close ()

... datatransfer

DatagramSocket ()

close ()

...

DatagramPacket ()receive ()

DatagramSocket ()

DatagramPacket ()send ()

DatagramPacket ()receive ()

− very simple data transmission with low overhead

− unreliable (messages may arrive out of order, or not at all)

− send: create a datagram packet with

♦ data

♦ length of data field

♦ destination address

♦ destination port

− receive: create a datagram packet with

♦ receive buffer

♦ size of receive buffer

⇒ on return the datagram packet contains the data, number of

bytes received, and source address and source port

− a DatagramSocket is reusable for arbitrary datagram packets to

arbitrary destinations

Parallel Programming Slide 4 - 21

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

• display some information about sockets in use (only with Linux)

gross@kea:/home/gross/socket > sockserv I'm a non-blocking echo server. PID: 444 I stop my work, if you type <Ctrl-c> or <Strg-c>. gross@kea:/home/gross/socket > socklist type port inode uid pid fd name tcp 8888 60046 500 444 3 sockserv tcp 6000 38283 500 0 0 ... gross@kea:/home/gross/socket > java sockserv I'm a non-blocking echo server listening at port 88 88 I stop my work, if you type <Ctrl-c> or <Strg-c>. gross@kea:/home/gross/socket > socklist type port inode uid pid fd name tcp 8888 67177 500 467 4 java tcp 6000 38283 500 0 0 ...

• "bind ()" reports an error

gross@kea:/home/gross/socket > sockserv I'm a non-blocking echo server. PID: 493 I stop my work, if you type <Ctrl-c> or <Strg-c>. line 144: "bind ()" failed: Address already in use gross@kea:/home/gross/socket > socklist type port inode uid pid fd name tcp 8888 0 0 0 0 tcp 6000 38283 500 0 0

− there is no process assigned to the socket

− happens sometimes if you finish the server with <Ctrl-c> and

restart it at once

− after some time (about a minute) the socket is available again

Parallel Programming Slide 4 - 22

Hochschule Fulda - University of Applied Sciences, Prof. Dr. S. Groß

Exercise 4-1:

Implement a TCP echo server with POSIX threads instead of child

processes for each connection.

Exercise 4-2:

Implement a client and an echo server for UDP instead of TCP.


Recommended