Download presentation
Presentation is loading. Please wait.
1
Java Sockets Programming - Fundamentals
Goal: Make communication between computations possible Interprocess Communication (IPC): mechanism for exchanging messages between two computing process (running on the same or different machines) Examples: pipes or socket pairs first introduced in Berkeley Unix, remote procedure calls (RPC) and remote method invocation (RMI) of Java first introduced by Sun. socket: Low level programming primitive that allows processes to exchange information through a communication channel Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
2
CS 667: Socket Fundamentals Copyright Zlateva
Unix I/O and pipes Main idea: Implement interprocess communication following the Unix I/O paradigm of Open Read/Write Close. obtain permission to connect receive/send info terminate connection Background: A Unix process has a set of I/O descriptors, to which the process writes to/reads from and that refer to files and devices. A Unix pipe is a pseudo-file that connects two processes, provided the processes inherit file descriptors for that pipe from a common ancestor, e.g. cat hello.java | lpr Unix shell creates two processes with a pipe between them: cat reads hello.java, and instead of writing to the standard output (screen) sends it through the pipe to lpr which sends it to the printer Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
3
CS 667: Socket Fundamentals Copyright Zlateva
Pipes and Sockets OS (Unix) Pipes: A and B must be related Unrelated processes cannot communicate through pipe pipe Process B (lpr) Process A (cat) Note: Unrelated processes can communicate through files - one process reading to the file, the other checking periodically; this still does not allow communication over network Network communication channel Process B Process A Sockets: Interface to protocol stack (TCP or UDP, IP) that is part of the OS kernel OS OS History: The socket API was introduced in 4.2BSD, Computer System Research Group (CSRG) at Berkeley, The networking code (TCP/IP protocol stacks, socket interface, telnet, ftp client & server), was developed independently from the AT&T-derived Unix code. Merged in 4.4BSD-Lite, 1994 (Ste 1998,p.19) Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
4
Socket in OSI and Internet Protocol Suit
Application Presentation (data format, conversion) Session (multi- threading)- message Transport segment/message Network - datagram/packet DataLink – frames Physical – bit Application: e.g. FTP, telnet, SMTP, , etc. Network adapters & Device drivers typically run in OS IP Internet Protocol TCP Transmission Control Protocol UDP User Datagram Protocol Raw Socket Application Details: Sockets Communication Details: Sending data, waiting for acknowledgement, sequencing data to arrive in order, calculating and verifying checksums, etc. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
5
End-to-End Communication Types
Connection-Oriented or Stream Reliable ordered two-way connection service in two stages: 1. Connection setup: Establishes virtual connection from source to host (connection state established) 2. Transfer Protocol: TCP/IP* Connectionless or Datagram* Unreliable ("transmit and pray") two-way connection service; simple extension of the underlying host-to-host IP delivery service to process-to process Every packet (datagram) must contain full destination information (address of receiving socket and local descriptors) Packets can be sent any time anywhere (no need to establish connection state); Packets sent independently; Protocol: UDP/IP *Virtual Circuit technologies, such as X.25, Frame Relay, ATM, also provide a connection-oriented reliable/ordered delivery service (PeDa 2003). However they are network layer protocols, (as is IP), packets follow same route, and delivery is assumed reliable/ordered/hop-by-hop. As opposed to this TCP assumes unreliable best-effort delivery as provided by IP, datagrams may take different routes, and are assembled into a TCP segment at the ends of the communication channel, i.e. and end-to-end as opposed to hop-to-hop approach (PeDa 2003) Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
6
CS 667: Socket Fundamentals Copyright Zlateva
Streams vs. Datagrams TCP Stream additional time for establishing the connection less information transmitted as no need to include the address of receiving socket and local descriptors with each packet no size limit on information size that can be sent to a specific location good for services requiring transfer of data of indefinite length, e.g. remote login (rlogin, telnet), ftp UDP Datagram no connection set up time more information transmitted than streams as all packets must include local descriptors and address of receiving socket not known if packet delivered. successive packets may have different routes and there is no guarantee they will arrive in order. datagram size limited to 64 kB appropriate if application protocol handles reliability, application requires multicast, or cannot tolerate TCP overhead For more on TCP vs. UDP see (Ste 1998, p. 541) Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
7
CS 667: Socket Fundamentals Copyright Zlateva
Socket Types Socket Type Communication Type Protocol Stack SOCK_STREAM stream, virtual circuit TCP/IP SOCK_DGRAM datagram, connectionless UDP/IP message-oriented SOCK_RAW either- bypasses transmission /IP layer; allows higher control of packet transmission not supported by Java for security reasons Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
8
Socket Types & Protocol Stacks - Examples
TCP socket ICMP IGMP IP APR Link RARP UDP tftp mrouted TCP ftp ping traceroute UDP socket RAW socket Applications: ping packet internet groper: sends ICMP echo request to some IP address and receives ICMP echo reply from that node traceroute determines path of IP datagrams from host to destination ftp file transmission protocol (here the application that uses it) tftp trivial file transmission protocol used to bootstrap systems on LAN not on WAN mrouted multicast routing Protocols: ICMP Internet Control Message Protocol: handles TCP/IP internally generated messages & control messages between routers and hosts; usually not used for application IGMP Internet Group Management Protocol: used for multicasting APR Address Resolution Protocol: maps IP addresses to hardware addresses RARP Reverse Address Resolution Protocol: maps hardware addresses to IP For more details see (Ste 1998) Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
9
CS 667: Socket Fundamentals Copyright Zlateva
Naming and Routing IP datagrams are delivered, routed, from host to destination based on a 32 bit identifier, called IP address, that contains the Network ID and the Host ID. The address is often represented through 4 decimal numbers in the range of 0-255, (one for each 8 bit group), e.g. 128.xxx.xxx.xxx or through a symbolic name, such as metcs.bu.edu The correspondence between symbolic and numerical identifiers is provided by a naming service, known as the Domain Name Service (DNS) To meet the requirements of different types of organizations there are 5 IP address classes that provide address ranges with different lengths of the network and host IDs as appropriate for the corresponding organization type. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
10
CS 667: Socket Fundamentals Copyright Zlateva
Internet Addresses Class A: large networks: more than 65,536 (>16 bits) hosts Network ID Host ID 0… … … …255 Class B: medium size networks: ,536 (8-16 bits) hosts Network ID Host ID 128… … … …255 Class C: small networks: (<=8 bits) hosts Network ID Host ID 192… … … …255 Class D: Multicast 224… … … …255 Class E: Reserved for future use 240… … … …255 Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
11
Data Streams (review) -Some more important classes from the java.io
InputStream/ OutputStream: abstract class, provides read()/ write() method; created and tied to socket through the Socket method getInputStream()/ getOuputStream() that returns an input/output stream for this socket. Reader/ Writer: abstract class for writing to character (text) streams; the only methods a subclass must implement are write(char[], int, int), flush(), and close(); most subclasses override some of the Reader/ Writer methods in order to provide higher efficiency, additional functionality, or both. InputStreamReader/ OutputStreamWriter extends Reader/ Writer: i/o stream reads/writes bytes and translates them into characters according to a specified character encoding. BufferedReader/BufferedWriter extends Reader/ Writer class: reads/writes text from a character-input stream, buffering characters so as to provide more efficient reading of characters, arrays, and lines. Should be wrapped around any Reader/Writer with costly operation, such as stream and file readers/writers to reduce number of required accesses to the stream. Ha methods such as readLine not defined in InputStream or InputStreamReader PrintWriter extends Writer class: prints formatted representations of objects to a text-output stream; creates necessary intermediate OuputStreamWriter; implements all of the print methods found in PrintStream but noy in OutputStream. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
12
CS 667: Socket Fundamentals Copyright Zlateva
Data Streams Examples I-Stream bound to Socket object s s.getInputStream() BufferedReader in = new BufferedReader(new InputStreamReader(<i-stream>); O-Stream bound to Socket object s s.getOutputStream() PrintWriter out = new PrintWriter (<o-stream>, true); autoFlush println() flushes output buffer Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
13
Data Streams (continued)
DataInputStream/DataOuputStream extends InputStream/ OutputStream; lets an application read primitive Java data types (as opposed to bytes) from an underlying input stream in a machine-independent way. ObjectInputStream/ObjectOuputStream extends InputStream/ OutputStream: reads/writes serialized objects (as opposed to primitive data types, text, or bytes); when written to file provides persistent storage : only objects that implement the java.io.Serializable interface can be written to ObjectInputStream; FilterInputStream/FilterOutputStream extends (non-buffered) InputStream/OutputStream by overriding their methods and providing additional functionality; improved performance by caching and flushing. FileWriter/FileReader extends Writer/Reader class for reading character files FileInputStream/FileOutputStream extends InputStream/ OutputStream for reading data from a File or from a FileDescriptor. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
14
Java Socket Types in java.net package
Class Description Socket TCP endpoint, client socket ServerSocket TCP endpoint, server socket DatagramSocket UDP endpoint, for sending and receiving datagrams DatagramPacket UDP endpoint, for sending datagrams MulticastSocket extends DatagramSocket for sending and receiving IP multicast packets. A MulticastSocket is a (UDP) DatagramSocket, with additional capabilities for joining "groups" of other multicast hosts on the internet. URL Uniform Resource Locator that points to an object on the Internet such as a simple file, or more complicated object such as query to a database or a search engine. URLConnection abstract class; superclass of all classes that represent a communications link between the application and a URL (e.g. CGI-bin script,DayTime service); connection is established in several steps; Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
15
Opening a TCP Connection - Client Side
Opening a TCP client Socket myClient = null; try { myClient = new Socket("host", PortNumber); } catch (UnknownHostException uhe){ uhe.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } public Socket(String host, int port) throws UnknownHostException, IOException Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
16
Opening a TCP Connection - Server Side
public ServerSocket(int port) throws IOException Opening a TCP server socket ServerSocket myService = null; try { myService = new SeverSocket(PortNumber); } catch(IOException e){ e.printStackTrace(); } Opening a TCP client type socket from server to listen and accept connection Socket serviceClient = null; //NOTE: client socket type serviceClient= myService.accept(); public Socket accept() throws IOException Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
17
Creating Input Streams for TCP Connection
Creating an Input stream on the Client side BufferedReader is = null; try{ is = new BufferedReader( new InputStreamReader(myClient.getInputStream())); } catch(IOException ioe){ ioe.printStackTrace(); } Creating an Input stream on the Server side new InputStreamReader(serviceClient.getInputStream())); Wrapping with BufferedReader for efficiency Reading the input stream: bytes->char Input stream to Client Socket Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
18
Creating Output Streams for TCP Connection
Creating an Output stream on the Client side DataOutputStream os = null; try{ os = new DataOutputStream(myClient.getOutputStream()); } catch(IOException ioe){ ioe.printStackTrace(); } Similarly on the Server side os = new DataOutputStream(serviceClient.getOutputStream()); Output stream to client Socket DataOtuputStream for writing primitive data types Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
19
Closing a TCP Connection
Closing the TCP connection on the Client side try{ os.close(); is.close(); myClient.close(); } catch(IOException ioe){ ioe.printStackTrace(); } Closing the TCP connection on the Server side serviceClient.close(); Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
20
CS 667: Socket Fundamentals Copyright Zlateva
Example1: "Greetings" "… and Salutations…" Files: SimpleServer.java, SimpleClient.java Server Side Client Side checkServer TESTPORT clientSocket is os c1 is os SimpleServer started... Please input password: Greetings Greetings we received: Greetings ....and Salutations... Got from server ....and Salutations... Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
21
One Server Should Handle Multiple Clients and Salutations
Server Side Client Side c1 is os checkServer TESTPORT c1 is os clientSocket is os Problem: In Example 1 the server can handle only one client at a time. The read() method blocks and waits for client input, i.e. if server attempts to read from a client it needs to get input from this client, before being able to read from another client Solution: multiple threads on server side, each thread handles one client Note: Another solution is to write a nonblocking server, which is usually the inferior solution. For more details see HSH 1999, p.315. clientSocket is os . Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
22
Symbolic and Numerical Internet Addresses
Problem: Being able to transform symbolic in numerical Internet Ids and vice versa, i.e. having access to the correspondence symbolic ID numerical ID Java class InetAddress represents an Internet Protocol (IP) address. Methods getAddress() Returns the raw IP address (byte array) of this InetAddress object. The result is in network byte order: the highest order byte of the address is in getAddress()[0]. Ex: InetAddress rawAddress; byte [] rawAddress = address.getAddress(); // rawAddress[0] is the highest order byte Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
23
Symbolic and Numerical Internet Addresses (continued)
. Methods getLocalHost() Returns the IP address of the local host. throws: UnknownHostException if no IP address for the host could be found (see SimpleServer code). getByName( <string-host>) Determines the IP address of a host, given the name (as string) of the host. isMulticastAddress() check if the InetAddress is a IP multicast address. toString() Converts this IP address to a String; returns a string representation of this IP address. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
24
Creating Clients for Existing Services
Goal: Program a client to use existing Internet services, such as SMTP (Simple Mail Transfer Protocol), ping, finger Main Idea: Using the service means following the protocol (the language or the rules for exchanging information) that have been established for this service. In other words the client and server must speak the same language, or more precisely the client must know the commands the server understands. The implementation of the client is based on the simple idea to send the commands through a socket to the server and receive the reply. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
25
CS 667: Socket Fundamentals Copyright Zlateva
Examples: SMTP, finger From Unix shell From socket program SMTP % telnet metcs.bu.edu smptSocket = new Socket("metcs.bu.edu", 25); HELO os.writeBytes("HELO\n"); MAIL os.writeBytes("MAIL From: "); etc. finger % finger os.writeBytes(" "); Output stream bound to socket Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
26
Internet Port Services
The first 1024 ports (0…1023) are reserved for specific well known Internet services. Each service has a corresponding protocol. The Internet standards are established through and interactive process of development known as the "Request for Comment" (RFC), and the specifications are available as RFC or standards (STD) Port Protocol RFC 7 Echo RFC 862 13 DayTime RFC 867 20 ftp RFC 959 25 SMPT RFC 821 and other extensions 80 HTTP RFC 2616 For further information see (HSH 1999, p.274ff) Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
27
CS 667: Socket Fundamentals Copyright Zlateva
References: (HoCo 2003) Cay S. Horstmann, Gary Cornell: Core Java 2. Volume 2: Advanced Features. Prentice Hall. ISBN: : 5th ed. A clear and detailed discussion of topics with good examples, but does not contain all topics covered in the course. Material covered in the last edition is essentially the same as in previous editions, but is presented more concisely, with J2SE version 1.3/1.4. Ch.3 Networking (PeDa 2003) Larry L. Peterson, Bruce S. Davie: Computer Networks - A Systems Approach, 3d ed, Morgan Kaufman: The standard text for a serious student of networks. (HSH 1999) Merlin Hughes, Michael Shoffner, Derek Hamner: Java Network Programming : A Complete Guide to Networking, Streams, and Distributed Computing. Manning Publications Company; ISBN: X: As the title suggests streams as the crux of network programming. (Ste 1998) W.Richard Stevens: Unix Network Programminig, Vol.1, Networking APIs: Sockets and XTI , Prentice Hall: A classic of Unix programming. Fall 2003 CS 667: Socket Fundamentals Copyright Zlateva
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.