Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.

Slides:



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

SOCKET PROGRAMMING WITH MOBILE SOCKET CLIENT DEARTMENT OF COMPUTER SCIENCE IOWA STATE UNIVERSITY.
Referring to Java API Specifications
UDP Datagrams and Sockets Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University.
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.
© 2003 Andrea Calvagna 5/16/2015 Java Sockets and Server Sockets Low Level Network Programming Andrea Calvagna
© 1999 Elliotte Rusty Harold 5/16/2015 Java Sockets and Server Sockets Low Level Network Programming Elliotte Rusty Harold
Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
Prepared By E. Musa Alyaman1 Java Network Programming TCP.
Socket Programming.
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.
WECPP1 Java networking Jim Briggs based on notes by Amanda Peart based on Bell & Parr's bonus chapter
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
1 Networking with Java 2: The Server Side. 2 Some Terms Mentioned Last Week TCP -Relatively slow but enables reliable byte-stream transmission UDP -Fast.
Lecture 11 Java Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger and Joonbok Lee.
Client/Server In Java An Introduction to TCP/IP and Sockets.
Networking Support In Java Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Datagram Programming A datagram is an independent, self-contained message sent over the network whose arrival, arrival time, and content are not guaranteed.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
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)
Socket Programming (C/Java)
CS 352-Socket Programming & Threads Dept. of Computer Science Rutgers University (Thanks,this slides taken from er06/
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Multicast Sockets What is a multicast socket?
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:
1 CSCD 330 Network Programming Winter 2015 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 6 Application.
UDP vs TCP UDP Low-level, connectionless No reliability guarantee TCP Connection-oriented Not as efficient as UDP.
1 A TCP/IP Application Programming Perspective Chris Greenhalgh G53ACC.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
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 Using JAVA Asma Shakil Semester 1, 2008/2009.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
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.
Java Network Programming. We will learn how Java handles  Internet Addresses  URLs  Sockets  Server Sockets  UDP.
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.
Distributed Systems CS Project 1: File Storage and Access Kit (FileStack) Recitation 1, Aug 29, 2013 Dania Abed Rabbou and Mohammad Hammoud.
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 ( 李德成 )
1 CSCD 330 Network Programming Winter 2016 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 6 Application.
UDP User Datagram Protocol. About the UDP A commonly used transport protocol Does not guarantee either packet delivery or order The packets may travel.
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.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Network Programming. These days almost all devices.
Java 13. Networking public class SumTest {
Java.net CS-328 Dick Steflik.
Object-Orientated Analysis, Design and Programming
Lecture 21 Sockets 1 (Not in D&D) Date.
NETWORK PROGRAMMING CNET 441
Networking with Java 2.
An Introduction to TCP/IP and Sockets
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Network Programming Introduction
Network Programming Introduction
Implementation of UDP and TCP
CSCD 330 Network Programming
UNIT-6.
Networking.
CSCD 330 Network Programming
CSCD 330 Network Programming
NETWORK PROGRAMMING CNET 441
Java Socket Programming
Presentation transcript:

Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University

What We Will Discuss Today TCP stream java.net.Socket java.net.ServerSocket UDP packet Java.net.DatagramPacket java.net.DatagramSocket A Look at A Real Project Homework #1

Socket java.net.Socket is used by clients to make a bi-directional connection with server Socket constructors Socket(String hostname, int port) Socket(InetAddress addr, int port) Socket(String hostname, int port, InetAddress localAddr, int localPort) Socket(InetAddress addr, int port, InetAddress localAddr, int localPort) Creating socket Socket csweb = new Socket(“ 80);

Some Comments on Socket Socket() attempts to connect the underlying socket to the remote server No separate connect() method Cannot set or change remote host and port Socket constructors may block while waiting for the remote host to respond Depends on operating systems and timeout settings When performance is critical, programmer may want to create a separate thread to create a Socket

Sending and Receiving Data Data is sent and received with output and input streams There are methods to get an input stream for a socket and an output stream for the socket public InputStream getInputStream() public OutputStream getOutputStream() There's also a method to close a socket: public synchronized void close()

Socket Input & Output try { String s; Socket socket = new Socket(“ 80); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream pstream = new PrintStream(socket.getOutputStream()); pstream.println(“GET /”); while ((s = reader.readLine()) != null) { System.out.println(s); } catch (Exception e) { System.err.println(“Error: “ + e); }

Some Socket Options void setKeepAlive() void setReceiveBufferSize() void setSendBufferSize() void setTcpNoDelay() void setSoTimeout()

ServerSocket ServerSocket is used to by server to accept client connections ServerSocket constructor public ServerSocket(int port) public ServerSocket(int port, int backlog) public ServerSocket(int port, int backlog, InetAddress networkInterface) Creating a ServerSocket ServerSocket ss = new ServerSocket(80, 50); A closed ServerSocket cannot be reopened

Reading Data with a ServerSocket ServerSocket objects use their accept() method to connect to a client public Socket accept() accept() returns a Socket object, and its getInputStream() and getOutputStream() methods provide streams There are no getInputStream() or getOutputStream() methods for ServerSocket

A Simple Server try { ServerSocket ss = new ServerSocket(2345); Socket s = ss.accept(); PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("Hello There!"); pw.println("Goodbye now."); s.close(); } catch (IOException ex) { System.err.println(ex); }

DatagramPacket Constructor for receiving public DatagramPacket(byte[] data, int length) Constructor for sending public DatagramPacket(byte[] data, int length, InetAddress addr, int port) DatagramPacket Objects can be reused public synchronized void setAddress(InetAddress addr) public synchronized void setPort(int port) public synchronized void setData(byte data[]) public synchronized void setLength(int length)

DatagramSocket Constructor for sending public DatagramSocket() Constructor for receiving public DatagramSocket(int port) public DatagramSocket(int port, InetAddress addr)

Sending UDP Datagrams 1. Convert the data into byte array. 2. Create a DatagramPacket using the array 3. Create a DatagramSocket using the packet and then call send() method Example InetAddress dst = new InetAddess(“cs.iastate.edu"); String s = “This is my datagram packet" byte[] b = s.getBytes(); DatagramPacket dp = new DatagramPacket(b, b.length, dst, 2345); DatagramSocket sender = new DatagramSocket(); sender.send(dp);

Receiving UDP Datagrams Construct a DatagramSocket object on the port on which you want to listen Pass an empty DatagramPacket object to the DatagramSocket 's receive() method public synchronized void receive(DatagramPacket dp) The calling thread blocks until a datagram is received dp is filled with the data from that datagram Notes: Use getPort() and getAddress() to tell where the packet came from, getData() to retrieve the data, and getLength() to see how many bytes were in the data The received packet could be truncated to fit the buffer

Example of Receiving Datagram try { byte buffer = new byte[1024]; DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); DatagramSocket ds = new DatagramSocket(2345); ds.receive(incoming); byte[] data = incoming.getData(); String s = new String(data, 0, incoming.getLength()); System.out.println("Port" + incoming.getPort() + " on " + incoming.getAddress() + " sent this message:"); System.out.println(s); } catch …

A Mistake You Want to Avoid byte[] buf = new byte[1024]; DatagramPacket incoming = new DatagramPacket(buf, buf.length); DatagramSocket ds = new DatagramSocket(2345); for (;;) { ds.receive(incoming); byte[] data = incoming.getData(); new DataProcessor(data).start(); } class DataProcessor(byte[] data) extends Thread { // processing data[] … }

Correct Way byte[] buf = new byte[1024]; DatagramPacket incoming = new DatagramPacket(buf, buf.length); DatagramSocket ds = new DatagramSocket(2345); for (;;) { ds.receive(incoming); byte[] data = new byte[incoming.getLength()]; System.arraycopy(incoming.getData(), 0, data, 0, data.length); new DataProcessor(data).start(); } class DataProcessor(byte[] data) extends Thread { // processing data[] … }

Redundant Array of Inexpensive Disk RAID Management Monitor the health condition of RAID subsystems  disks, fans, power supplies, temperatures, etc. Report any failure instantly Provide disaster recovery  array rebuild, spare disks reassign, etc.

Remote and Centralized Storage Management

Homework #1 Server (java code) (UDP) Send beacon every minute Client (C code) (TCP) Send command and get result back Assigned on Monday, August 30, 2004 Due on 3:00PM, Wednesday, Sept. 15, 2004

Client Design: Two Threads BeaconSender: Send the following message to server every minute using UDP datagram struct BEACON { int ID; // randomly generated during startup int StartUpTime; // the time when the client starts char IP[4]; // the IP address of this client intCmdPort; // the client listens to this port for cmd } CmdAgent: Receive and execute remote commands and send results back using TCP socket. You implement two commands: (1) void GetLocalOS(char OS[16], int *valid) // OS[16] contains the local operation system name // valid = 1 indicates OS is valid (2) void GetLocalTime(int *time, int *valid) // time contains the current system clock // valid = 1 indicates time is valid

Server Design BeaconListener thread Receive beacons sent by clients For each new client, spawn a thread called ClientAgent ClientAgent(beacon) thread Send command GetLocalOS() to the corresponding client Get the result back and display the OS Send command GetLocalTime() to the corresponding client Get the result back and display the execution time