CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.

Slides:



Advertisements
Similar presentations
Socket UDP H. Fauconnier 1-1 M2-Internet Java. UDP H. Fauconnier M2-Internet Java 2.
Advertisements

Multiplexing/Demux. CPSC Transport Layer 3-2 Multiplexing/demultiplexing application transport network link physical P1 application transport network.
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
2: Application Layer 1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
User Datagram Protocol. Introduction UDP is a connectionless transport protocol, i.e. it doesn't guarantee either packet delivery or that packets arrive.
Prepared By E. Musa Alyaman1 User Datagram Protocol (UDP) Chapter 5.
1 Java Networking – Part I CS , Spring 2008/9.
2: Application Layer1 Data Communication and Networks Lecture 12 Java Sockets November 30, 2006.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Networking Support In Java 2 Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
System Programming Practical session 10 Java sockets.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.
1 Network Layers Application Transport Network Data-Link Physical bits.
2: Application Layer 1 Socket Programming TCP and UDP.
Socket Programming -What is it ? -Why bother ?. Basic Interface for programming networks at transport level It is communication end point Used for inter.
Babak Esfandiari (based on slides by Qusay Mahmoud)
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm.
Silberschatz, Galvin and Gagne  2002 Modified for CSCI 399, Royden, Operating System Concepts Operating Systems Lecture 12 Communicating over.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
CS4273: Distributed System Technologies and Programming I Lecture 7: Java Networking.
VIII. UDP Datagrams and Sockets. The User Datagram Protocol (UDP) is an alternative protocol for sending data over IP that is very quick, but not reliable:
CS 424/524: Introduction to Java Programming Lecture 25 Spring 2002 Department of Computer Science University of Alabama Joel Jones.
-1- Georgia State UniversitySensorweb Research Laboratory CSC4220/6220 Computer Networks Dr. WenZhan Song Associate Professor, Computer Science.
Socket Programming Lee, Sooyong
Network Programming and Sockets CPSC 363 Computer Networks Ellen Walker Hiram College (Includes figures from Computer Networking by Kurose & Ross, © Addison.
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
Socket Programming Tutorial. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
1 Chapter 28 Networking. 2 Objectives F To comprehend socket-based communication in Java (§28.2). F To understand client/server computing (§28.2). F To.
Java Sockets Programming
Java Socket programming. Socket programming with TCP.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
1 CSCD 330 Network Programming Spring 2014 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 7 Application.
1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r explicitly created, used, released by apps r client/server paradigm r two types of.
CSI 3125, Preliminaries, page 1 Networking. CSI 3125, Preliminaries, page 2 Inetaddress Class When establishing a connection across the Internet, addresses.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Networking Code CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
UDP User Datagram Protocol. About the UDP A commonly used transport protocol Does not guarantee either packet delivery or order The packets may travel.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
UDP Programming. Khoa CNTT – ĐH Nông Lâm TP. HCM 01/2007 2/86 Overview.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 33 Networking.
Network Programming Communication between processes Many approaches:
Object-Orientated Analysis, Design and Programming
Network Programming Introduction
Network Programming Introduction
Socket programming - Java
CSCD 330 Network Programming
CSCD 330 Network Programming
NETWORK PROGRAMMING CNET 441
Chapter 2: Application layer
Multiplexing/Demux.
Review Communication via paired sockets, one local and one remote
Presentation transcript:

CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming

2 Java Socket Communication Socket Communications in Java A socket is a bi-directional communication channel. It’s the most fundamental means of client-server communications across the network. There are two types of sockets: Stream sockets (connection oriented) and Datagram sockets (connectionless). Socket operations at the client side are different from those at the server side.

3 Stream Type Sockets Operations at Server Side A server is always waiting for incoming connection requests. So a server socket only specifies its own port number. create a server socket: ServerSocket (port) s = new ServerSocket(8189); accept an incoming connection: Socket snew = s.accept (); ServerClient Operations at Client Side A client needs to specify both host address and port number of the server. create a client socket: Socket (host, port) s = new Socket (“java.sun.com”, 8189) Close a Socket s.close();

4 Read / Write through a Socket get I/O data streams out of the socket s: InputStream ins = s.getInputStream (); OutputStream outs = s.getOutputStream(); Notice: “ins” and “outs” are of the same type as “System.in” and “System.out” get I/O reader and writer: BufferedReader in = new BufferedReader(new inputStreamReader(ins)); PrintWriter out = new PrintWriter(outs, true); // “true” makes socket flush read / write to I/O reader or writer: String str = in.readLine(); // end when meeting ‘\r’ out.println ( “Echo:” + str + “\r”);

5 An example of client connecting to a “time of a day” service class ClientSocket { public static void main(String[] args ) { Socket s = new Socket(args[0], Integer.parseInt(args[1])); BufferedReader in; in = new BufferedReader(new InputStreamReader(s.getInputStream())); while ((str = in.readLine()) != null) System.out.println(str); } class TimeSvr { public static void main(String[] args ) { ServerSocket s = new ServerSocket(11113); while (true) { Socket new_s = s.accept(); PrintWriter out = new PrintWriter(new_s.getOutputStream(), true); out.println(new Date()); new_s.close(); }

6 Example of a server class EchoSvr { public static void main(String[] args ) { String rdata; try { ServerSocket s = new ServerSocket(8900); Socket con = s.accept(); BufferedReader in; in = new BufferedReader(new InputStreamReader(con.getInputStream())); PrintWriter out = new PrintWriter(con.getOutputStream(), true); while ((rdata = in.readLine())!= null) { System.out.println(rdata); out.println(rdata); } } catch (Exception e) { System.out.println(e);} }

7 Multi-thread Server Implementations The server waits all the time for new client connections at the server socket by accept(). Each time when a connection accepted, the server spawns a new thread to handle the incoming connection, and itself is back waiting for new connections. while (true) { Socket incoming = s.accept( ); // wait here all the time new HandlerThread(incoming).start(); // return immediately } A thread dies after serving a client’s connection.

8 Implement Echo server as multi-threaded (Cont.) class ThreadEchoSvr { public static void main(String[] args ){ int i = 1; try { ServerSocket s = new ServerSocket(8189); while (true) { // remember the format of multi-thread!! Socket incoming = s.accept( ); new HandlerThread(incoming, i).start(); i++; // keep track the number of threads created. } } catch (Exception e) { System.out.println(e); }} }

9 Implement the Echo server as multi-threaded class HandlerThread extends Thread { Socket incoming; int cnt; HandlerThread(Socket s, int c) { incoming = s; cnt = c; } // pass parameters to threads via constructor public void run() { try { in = new BufferedReader(new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter(incoming.getOutputStream()); String str; while ((str = in.readLine()) != null) { out.println("Echo (" + counter + "): " + str + "\r"); if (str.equals("Bye.")) break; } incoming.close(); } catch (Exception e) { System.out.println(e); } } }

10 Applet Communicates with Server using Sockets For security reasons, applets can only make socket connections to its home web-server site. You need to run the server at the home web-server site (i.e., //personal.cs.cityu.edu.hk). Communication between the applet and the server bypasses the HTTP server. This is often used for the web applications that require both servers and clients interactions. public class AppletSocket extends Applet { public void init() { Socket s = new Socket(getCodeBase().getHost(), 8900); in = new BufferedReader(new InputStreamReader(s.getInputStream())); out = new PrintWriter(s.getOutputStream(), true); add("North", send = new JButton("send")); } public void actionPerformed (ActionEvent e) { if (e.getSource() == send) { out.println("This is a test "+y); rdata = in.readLine(); } ………… }

11 Datagram Sockets Java Datagram sockets are connectionless. The underlying protocol is usually UDP. The key concept of datagram sockets is DatagramPacket. Datagram Packet. A DatagramPacket object contains four parts: Sender’s InetAddress and port_no Receiver’s InetAddress and port_no byte [] data int data_size InetAddress object (defined in java.net.InetAddress). It contains two fields: hostname (a string), the name of the host, e.g., “sus1.cs.cityu.edu.hk” address (an int), a 32-bit IP address. An InetAddress object is created by: InetAddress InetAddress.getbyName(String hostname); e.g., InetAddress addr = InetAddress.getByName(“ue3k1.cs.cityu.edu.hk”) Send IP Send Port Recv IP Recv Port Len Data ……

12 Construct an Outgoing DatagramPacket DatagramPacket(byte buffer[], int len, InetAddress dest_ia, int dest_port) …….. String s = "This is a test of UDP Datagram sockets."; byte [] data = new byte[s.length()]; data = s.getBytes();// convert a string to an array of bytes to fit in a packet try { InetAddress addr = InetAddress.getByName("ue3k1.cs.cityu.edu.hk"); } catch (UnknowHostException e) { System.out.println(e);} int port = 33333; DatagramPacket outp = new DatagramPacket(data, data.length, addr, port); Note: The maximal size of a datagram packet is 64K (including UDP & IP headers). But, choosing packetsize of 8K is a good compromise.

13 Process an Incoming DatagramPacket Construct a DatagramPacket for receiving a packet DatagramPacket(byte buffer[], int len) Get information from a DatagramPacket A DatagramPacket contains both data and address, use the following methods to get information out of a DatagramPacket object: public InetAddress getAddress() it returns the remote host IP address. It returns the sender’s host IP address if it is a received datagram and the receiver’s host address if it’s a datagram to be sent. public int getPort() it returns the port number of the remote address of a datagram, similar to “getAddress()”. public int getLength() it returns the number of bytes of the data in the datagram (not include the header). public byte[] getData() it returns a byte array in the datagram. The number of bytes in the array should equal to the value returned from “getLength()”.

14 Example of processing a datagram packet ……… DatagramPacket inp = new DatagramPacket(data, 512); ds.receive(inp);// receive a packet from socket ds System.out.println(inp.getAddress()); // IP address System.out.println(inp.getPort()); System.out.println(inp.getLength()); System.out.println (new String(inp.getData())); ……… You often need the following methods to convert a byte array into a string when processing a received datagram: public String String(byte[] array) // convert a whole array public String String(byte[] array, int offset, int n)

15 Datagram Sockets Since the addresses are already embedded in datagrams, a Datagram socket is simply an input/output port for sending/receiving datagrams. Construct a socket at Server side public DatagramSocket(int port) The port number will be used by senders to send datagrams to this socket. Construct a socket at Client side public DatagramSocket() The client port number is assigned randomly. The server’s address & port number is embedded in datagrams. Send / Receive DatagramPackets public void send(DatagramPacket dp) public void receive(DatagramPacket dp)

16 Example of Datagram Sockets (server) class SvrUDPSocket { public static void main(String[] args ) { byte [] data = new byte[512]; try { int port = 10123; DatagramSocket ds = new DatagramSocket(port); DatagramPacket inp = new DatagramPacket(data, 512); ds.receive(inp);// receive datagram DatagramPacket outp = new DatagramPacket(inp.getData(), inp.getLength(), inp.getAddress(), inp.getPort()); ds.send(outp);// send datagram } catch (Exception e) { System.out.println(e);} }}

17 Example of Datagram Sockets (client) class ClntUDPSocket { public static void main(String[] args ) { String s = "This is a test of UDP Datagram sockets."; byte [] data = new byte[s.length()]; data = s.getBytes(); InetAddress addr = InetAddress.getByName("sus12.cs.cityu.edu.hk"); int port = 10123; DatagramPacket outp = new DatagramPacket(data, data.length, addr, port); DatagramSocket ds = new DatagramSocket(); ds.send(outp); DatagramPacket inp = new DatagramPacket(new byte[512], 512); ds.receive(inp); System.out.println(new String(inp.getData())); }