1 / 39

Data Communication and Networks

Data Communication and Networks. Lecture 11 Sockets in C and JAVA November 13, 2003 Joseph Conron Computer Science Department New York University jconron@cs.nyu.edu. Client/Server Paradigm. Basis for most application layer communications Client (typically) Initiates communication

chrisneal
Download Presentation

Data Communication and Networks

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Data Communication and Networks Lecture 11 Sockets in C and JAVA November 13, 2003 Joseph Conron Computer Science Department New York University jconron@cs.nyu.edu

  2. Client/Server Paradigm • Basis for most application layer communications • Client (typically) • Initiates communication • Sends requests and receives responses • Interacts with just a few servers at a time • Server (typically) • Waits for incoming requests • Receives requests and sends responses • Interacts with many clients concurrently

  3. The Socket Abstraction • Socket represents a service point used by an application to interact with a transport service. • In C, a socket is similar to a file descriptor and is used in read(), write(), and ioctl() calls • In Java, Socket is a class. • Java sockets provide (almost) all of the BSD socket semantics.

  4. Socket Programming Socket API • introduced in BSD4.1 UNIX, 1981 • explicitly created, used, released by apps • client/server paradigm • two types of transport service via socket API: • unreliable datagram (UDP) • reliable, byte stream-oriented (TCP)

  5. Client must contact server server process must first be running server must have created socket that accepts client’s connection request Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When client creates socket: client TCP establishes connection to server TCP When contacted by client, server TCP creates new socket for server process to communicate with client allows server to talk with multiple clients Socket Programming with TCP

  6. process process TCP with buffers, variables TCP with buffers, variables socket socket Socket-programming using TCP Socket:a door between application process and end-end-transport protocol (UCP or TCP) TCP service:reliable transfer of bytes from one process to another controlled by application developer controlled by application developer controlled by operating system controlled by operating system internet host or server host or server

  7. UDP: no “connection” between client and server no handshaking sender explicitly attaches IP address and port of destination server must extract IP address, port of sender from received datagram UDP: transmitted data may be received out of order, or lost UDP provides unreliable transfer of groups of bytes (“datagrams”) between client and server application viewpoint Socket programming with UDP

  8. Sockets in C • Host addresses separate from sockets: • Different functions for TCP or UDP • Not discussed: socket options via ioctl() (read about these in your own) • Compare this to the Java Socket class!

  9. Summary of socket system calls • socket- create a new socket • close - terminate use of a socket • bind - attach a network address to a socket • listen - wait for incoming messages • accept - begin using incoming connection • connect - make connection to remote host • send - transmit data through active connection • recv- receive data through active connection

  10. Server (connection-oriented protocol) socket() bind() listen() accept() Client blocks until connection from client socket() connection establishment connect() data (request) read() write() process request data (reply) write() read() Socket system calls for connection-oriented protocol

  11. Server (connectionless protocol) Socket system calls for connectionless protocol socket() bind() Client recvfrom() socket() blocks until data received from client bind() data (request) sendto() process request sendto() data (reply) revfrom() Not necessary in UDP!!

  12. socket descriptor = socket(protofamily, type, protocol) • Returns socket descriptor used in subsequent calls • protofamily selects protocol family; e.g.: • PF_INET - Internet protocols • PF_APPLETALK - AppleTalk protocols • type selects type of communication • SOCK_DGRAM - connectionless • SOCK_STREAM - connection-oriented • protocol specifies protocol within protocol family • IPPROTO_TCP - selects TCP • IPPROTO_UDP - selects UDP

  13. close close(descriptor) • Terminates use of socket descriptor • descriptor contains descriptor of socket to be closed

  14. bind bind(socket, localaddr, address) • Initially, socket has no addresses attached • bind selects either local, remote or both addresses • server binds local port number for incoming messages • client binds remote address and port number to contact server

  15. Socket address formats • Because sockets can be used for any protocols, address format is generic: struct sockaddr { u_char sa_len; /* total length of address */ u_char sa_family; /* family of the address */ char sa_data[14]; /* address */ } • For IP protocols, sa_data hold IP address and port number: struct sockaddr_in { u_char sin_len; /* total length of address */ u_char sin_family; /* family of the address */ u_short sin_port; /* protocol port number */ struct in_addr sin_addr; /* IP address */ char sin_zero[8] /* unused */ } • First two fields match generic sockaddr structure • Remainder are specific to IP protocols • INADDR_ANY interpreted to mean "any" IP address

  16. listen listen(socket, queuesize) • Server uses listen to wait for incoming connections • socket identifies socket through which connections will arrive (address) • New connection requests may arrive while server processes previous request • Operating system can hold requests on queue • queuesizesets upper limit on outstanding requests

  17. accept accept(socket, caddress, caddresslen) • Server uses accept to accept the next connection request • accept call blocks until connection request arrives • Returns new socket with server's end of new connection • Old socket remains unchanged and continues to field incoming requests • caddress returns struct sockaddr client address; format depends on address family of socket • caddresslen returns length of address

  18. connect connect(socket, saddress, saddresslen) • Client uses connect to establish connection to server • Blocks until connection completed (accepted) • socket holds descriptor of socket to use • saddress is a struct sockaddr that identifies server • saddresslen gives length of saddress • Usually used with connection-oriented transport protocol • Can be used with connectionless protocol • Marks local socket with server address • Implicitly identifies server for subsequent messages

  19. send send(socket, data, length, flags) • Used to send data through a connected socket • socket identifies socket • data points to data to be sent • length gives length of data (in bytes) • flags indicate special options

  20. sendto, sendmsg sendto(socket, data, length, flags, destaddress, addresslen) sendmsg(socket, msgstruct, flags) • Used for unconnected sockets by explicitly specifying destination • sendto adds additional parameters: • destaddress - struct sockaddr destination address • addresslen - length of destaddress • sendmsg combines list of parameters into single structure: struct msgstruct { struct sockaddr *m_addr; /* ptr to destination address */ struct datavec *m_vec; /* pointer to message vector */ int m_dvlength; /* num. of items in vector */ struct access *m_rights; /* ptr to access rights list */ int m_alength; /* num. of items in list */ }

  21. recv recv(socket, buffer, length, flags) • Used to receive incoming data through connected socket • socket identifies the socket • Data copied into buffer • At most length bytes will be recved • flags give special options • Returns number of bytes actually received • 0 implies connection closed • -1 implies error

  22. recvfrom, recvmsg recvfrom(socket, buffer, length, flags, sndraddress, addresslen) recvmsg(socket, msgstruct, flags) • Like recvfrom and recvmsg (in reverse!) • Address of source copied into sndraddress • Length of address in addresslen • recvmsg uses msgstruct for parameters

  23. Other procedures • getpeername - address of other end of connection • getsockname - current address bound to socket • setsockopt - set socket options

  24. Sockets and processes • Like file descriptors, sockets are inherited by child processes • Socket disappears when all processes have closed it • Servers use socket inheritance to pass incoming connections to slave server processes

  25. Select • Wait for first fd in a set to become ready, or a timeout. • Use for asynchronous I/O or multiple concurrent operations within one thread. #include <sys/types.h> #include <sys/time.h> int select (width, readfds, writefds, exceptfds, timeout); int width; fd_set *readfds, *writefds, *exceptfds; struct timeval *timeout;

  26. Select Example int main(void) { fd_set rfds; struct timeval tv; int retval; /* Watch stdin (fd 0) to see when it has input. */ FD_ZERO(&rfds); FD_SET(0, &rfds); /* Wait up to five seconds. */ tv.tv_sec = 5; tv.tv_usec = 0; retval = select(1, &rfds, NULL, NULL, &tv); if (retval) printf("Data is available now.\n"); /* FD_ISSET(0, &rfds) will be true. */ else printf("No data within five seconds.\n"); exit(0); }

  27. What do I need to include? - In Unix: #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <netinet/in.h> - In Windows NT/95 #include <windows.h> #include <sys/types.h> #include <winsock.h>

  28. Sockets in JAVA • InetAddress • Represents an IP Address • ServerSocket • Passive socket (server) • Socket • Active socket (client) • DatagramSocket • UDP socket • DatagramPacket • Represents a UDP datagram

  29. create socket, connect to hostid, port=x create socket, port=x, for incoming request: clientSocket = Socket() welcomeSocket = ServerSocket() TCP connection setup wait for incoming connection request connectionSocket = welcomeSocket.accept() send request using clientSocket read request from connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket Client/server socket interaction: TCP Server (running on hostid) Client

  30. Example: Java client (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); Create input stream Create client socket, connect to server Create output stream attached to socket

  31. Example: Java client (TCP), cont. Create input stream attached to socket BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Send line to server Read line from server

  32. Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); Create welcoming socket at port 6789 Wait, on welcoming socket for contact by client Create input stream, attached to socket

  33. Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } } Create output stream, attached to socket Read in line from socket Write out line to socket End of while loop, loop back and wait for another client connection

  34. Client create socket, port=x, for incoming request: serverSocket = DatagramSocket() create socket, clientSocket = DatagramSocket() Create, address (hostid, port=x, send datagram request using clientSocket read request from serverSocket write reply to serverSocket specifying client host address, port umber read reply from clientSocket close clientSocket Client/Server socket interaction: UDP Server (running on hostid)

  35. Example: Java client (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket Translate hostname to IP address using DNS

  36. Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Send datagram to server Read datagram from server

  37. Example: Java server (UDP) import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 Create space for received datagram Receive datagram

  38. Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Get IP addr port #, of sender Create datagram to send to client Write out datagram to socket End of while loop, loop back and wait for another datagram

  39. Socket Programming Summary • BSD sockets are the standard • The basic interface (C) is arcane • Socket class in Java makes life easier without sacrificing functionality • But one could hide the complexity of C with well thought out functions (see Comer, D.E. and Stevens, D.L. Internetworking with TCP/IP: Volume III: Client-Server Programming and Applications, BSD socket version chapter 7)

More Related