Java Socket Programming

Slides:



Advertisements
Similar presentations
2: Application Layer1 Socket programming Socket API r introduced in BSD4.1 UNIX, 1981 r Sockets are explicitly created, used, released by applications.
Advertisements

Client-Server Paradigm and Performance L. Grewe. 2 Review: Basic Client-Server Request/Reply Paradigm Typical Internet app has two pieces: client and.
Network Programming and Java Sockets
Application Layer 2-1 Chapter 2 Application Layer Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Application Layer – Lecture.
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.
9/23/2003-9/25/2003 Sockets & DNS September 23-25, 2003.
1 Creating a network app Write programs that  run on different end systems and  communicate over a network.  e.g., Web: Web server software communicates.
2: Application Layer1 Data Communication and Networks Lecture 12 Java Sockets November 30, 2006.
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.
1 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
Internet and Intranet Protocols and Applications Lecture 4: Application Layer 3: Socket Programming February 8, 2005 Arthur Goldberg Computer Science Department.
Lecture 11 Java Socket Programming CPE 401 / 601 Computer Network Systems slides are modified from Dave Hollinger and Joonbok Lee.
Socket programming with UDP and TCP. Socket Programming with TCP Connection oriented – Handshaking procedure Reliable byte-stream.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
1 Network Layers Application Transport Network Data-Link Physical bits.
Protocols Rules for communicating between two entities (e.g., a client and a server) “A protocol definition specifies how distributed system elements interact.
2: Application Layer 1 Socket Programming Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross Addison-Wesley,
JAVA Socket Programming Joonbok Lee KAIST.
2: Application Layer 1 Socket Programming TCP and UDP.
Network Applications: UDP and TCP Socket Programming Y. Richard Yang 9/17/2013.
JAVA Socket Programming Source: by Joonbok Lee, KAIST, 2003.
ECE5650: Network Programming
1 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.
2: Application Layer1 Chapter 2 Application Layer Computer Networking: A Top Down Approach Featuring the Internet, 2 nd edition. Jim Kurose, Keith Ross.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
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.
CS 3830 Day 11 Introduction : Application Layer 2 Server-client vs. P2P: example Client upload rate = u, F/u = 1 hour, u s = 10u, d min ≥ u s.
 Socket  The combination of an IP address and a port number. (RFC 793 original TCP specification)  The name of the Berkeley-derived application programming.
Chapter 2 Application Layer Computer Networking: A Top Down Approach, 5 th edition. Jim Kurose, Keith Ross Addison-Wesley, April A note on the use.
Winter 2002Suprakash Datta1 Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
-1- Georgia State UniversitySensorweb Research Laboratory CSC4220/6220 Computer Networks Dr. WenZhan Song Associate Professor, Computer Science.
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.
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.
Socket Programming Tutorial. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
Java Sockets Programming
Java Socket programming. Socket programming with TCP.
NETWORK PROGRAMMING.
Socket-Programming.  Establish contact (connection).  Exchange information (bi-directional).  Terminate contact.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
2: Application Layer1 Socket programming Socket API Explicitly created, used, released by apps Client/server paradigm Two types of transport service via.
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.
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.
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.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
1 All rights reserved to Chun-Chuan Yang Upon completion you will be able to: The OSI Model and the TCP/IP Protocol Suite Understand the architecture of.
Topic: Network programming
Socket Programming Socket Programming Overview
CSE524: Lecture 3 Application layer.
Transport layer (last part) Application layer
DNS: Domain Name System
Socket programming with TCP
CSCD 330 Network Programming
Chapter 2: outline 2.1 principles of network applications
Socket programming - Java
CSCD 330 Network Programming
Socket Programming Socket Programming Overview
Socket Programming.
CSCD 330 Network Programming
Socket Programming 2: Application Layer.
DNS: Domain Name System
CPSC 441 UDP Socket Programming
Chapter 2: Application layer
DNS: Domain Name System
DNS: Domain Name System
Socket Programming with UDP
Presentation transcript:

Java Socket Programming

Java Sockets Programming The package java.net provides support for sockets programming (and more). Typically you import everything defined in this package with: import java.net.*; Java Socket Programming

Classes InetAddress Socket ServerSocket DatagramSocket DatagramPacket Java Socket Programming

InetAddress class static methods you can use to create new InetAddress objects. getByName(String host) getAllByName(String host) getLocalHost() InetAddress x = InetAddress.getByName( “cse.unr.edu”); Throws UnknownHostException Java Socket Programming

Sample Code: Lookup.java Uses InetAddress class to lookup hostnames found on command line. > java Lookup cse.unr.edu www.yahoo.com cse.unr.edu:134.197.40.9 www.yahoo.com:209.131.36.158 Java Socket Programming

InetAddress a = InetAddress.getByName(hostname); try { InetAddress a = InetAddress.getByName(hostname); System.out.println(hostname + ":" + a.getHostAddress()); } catch (UnknownHostException e) { System.out.println("No address found for " + hostname); } Java Socket Programming

Socket class Corresponds to active TCP sockets only! client sockets socket returned by accept(); Passive sockets are supported by a different class: ServerSocket UDP sockets are supported by DatagramSocket Java Socket Programming

JAVA TCP Sockets java.net.Socket Implements client sockets (also called just “sockets”). An endpoint for communication between two machines. Constructor and Methods Socket(String host, int port): Creates a stream socket and connects it to the specified port number on the named host. InputStream getInputStream() OutputStream getOutputStream() close() java.net.ServerSocket Implements server sockets. Waits for requests to come in over the network. Performs some operation based on the request. ServerSocket(int port) Socket Accept(): Listens for a connection to be made to this socket and accepts it. This method blocks until a connection is made. Java Socket Programming

Sockets Client socket, welcoming socket (passive) and connection socket (active) Java Socket Programming

Socket Constructors Constructor creates a TCP connection to a named TCP server. There are a number of constructors: Socket(InetAddress server, int port); Socket(InetAddress server, int port, InetAddress local, int localport); Socket(String hostname, int port); Java Socket Programming

Socket Methods void close(); InetAddress getInetAddress(); InetAddress getLocalAddress(); InputStream getInputStream(); OutputStream getOutputStream(); Lots more (setting/getting socket options, partial close, etc.) Java Socket Programming

Socket I/O Socket I/O is based on the Java I/O support in the package java.io InputStream and OutputStream are abstract classes common operations defined for all kinds of InputStreams, OutputStreams… Java Socket Programming

InputStream Basics // reads some number of bytes and // puts in buffer array b int read(byte[] b); // reads up to len bytes int read(byte[] b, int off, int len); Both methods can throw IOException. Both return –1 on EOF. Java Socket Programming

OutputStream Basics // writes b.length bytes void write(byte[] b); // writes len bytes starting // at offset off void write(byte[] b, int off, int len); Both methods can throw IOException. Java Socket Programming

ServerSocket Class (TCP Passive Socket) Constructors: ServerSocket(int port); ServerSocket(int port, int backlog); ServerSocket(int port, int backlog, InetAddress bindAddr); Java Socket Programming

throw IOException, SecurityException ServerSocket Methods Socket accept(); void close(); InetAddress getInetAddress(); int getLocalPort(); throw IOException, SecurityException Java Socket Programming

Socket programming with TCP Example client-server app: client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream) server reads line from socket server converts line to uppercase, sends back to client client reads, prints modified line from socket (inFromServer stream) Client process Input stream: sequence of bytes into process output stream: sequence of bytes out of process client TCP socket Java Socket Programming

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

TCPClient.java 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());

TCPClient.java 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();                    } } Java Socket Programming

TCPServer.java 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()));

TCPServer.java            DataOutputStream  outToClient =              new DataOutputStream(connectionSocket.getOutputStream());            clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence);         } Java Socket Programming

Sample Echo Server TCPEchoServer.java Simple TCP Echo server. Based on code from: TCP/IP Sockets in Java Java Socket Programming

UDP Sockets DatagramSocket class DatagramPacket class needed to specify the payload incoming or outgoing Java Socket Programming

Socket Programming with UDP Connectionless and unreliable service. There isn’t an initial handshaking phase. Doesn’t have a pipe. transmitted data may be received out of order, or lost Socket Programming with UDP No need for a welcoming socket. No streams are attached to the sockets. the sending hosts creates “packets” by attaching the IP destination address and port number to each batch of bytes. The receiving process must unravel to received packet to obtain the packet’s information bytes. Java Socket Programming

JAVA UDP Sockets In Package java.net java.net.DatagramSocket A socket for sending and receiving datagram packets. Constructor and Methods DatagramSocket(int port): Constructs a datagram socket and binds it to the specified port on the local host machine. void receive( DatagramPacket p) void send( DatagramPacket p) void close() Java Socket Programming

DatagramSocket Constructors DatagramSocket(int port); DatagramSocket(int port, InetAddress a); All can throw SocketException or SecurityException Java Socket Programming

Datagram Methods Lots more! void connect(InetAddress, int port); void close(); void receive(DatagramPacket p); void send(DatagramPacket p); Lots more! Java Socket Programming

Datagram Packet Contain the payload (a byte array Can also be used to specify the destination address when not using connected mode UDP Java Socket Programming

DatagramPacket Constructors For receiving: DatagramPacket( byte[] buf, int len); For sending: DatagramPacket( byte[] buf, int len InetAddress a, int port); Java Socket Programming

DatagramPacket methods byte[] getData(); void setData(byte[] buf); void setAddress(InetAddress a); void setPort(int port); InetAddress getAddress(); int getPort(); Java Socket Programming

Example: Java client (UDP) process Input: receives packet (TCP received “byte stream”) Output: sends packet (TCP sent “byte stream”) client UDP socket Java Socket Programming

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

UDPClient.java 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();

UDPClient.java       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();       } } Java Socket Programming

UDPServer.java 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);             String sentence = new String(receivePacket.getData());

UDPServer.java      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);       } } Java Socket Programming

Sample UDP code UDPEchoServer.java Simple UDP Echo server. Test using nc as the client (netcat): > nc –u hostname port Java Socket Programming

Socket functional calls socket (): Create a socket bind(): bind a socket to a local IP address and port # listen(): passively waiting for connections connect(): initiating connection to another socket accept(): accept a new connection Write(): write data to a socket Read(): read data from a socket sendto(): send a datagram to another UDP socket recvfrom(): read a datagram from a UDP socket close(): close a socket (tear down the connection) Java Socket Programming

Java URL Class Represents a Uniform Resource Locator scheme (protocol) hostname port path query string Java Socket Programming

Parsing You can use a URL object as a parser: URL u = new URL(“http://www.cs.unr.edu/”); System.out.println(“Proto:” + u.getProtocol()); System.out.println(“File:” + u.getFile()); Java Socket Programming

URL construction You can also build a URL by setting each part individually: URL u = new URL(“http”, www.cs.unr.edu,80,”/~mgunes/”); System.out.println(“URL:” + u.toExternalForm()); System.out.println(“URL: “ + u); Java Socket Programming

Retrieving URL contents URL objects can retrieve the documents they refer to! actually this depends on the protocol part of the URL. HTTP is supported File is supported (“file://c:\foo.html”) You can get “Protocol Handlers” for other protocols. There are a number of ways to do this: Object getContent(); InputStream openStream(); URLConnection openConnection(); Java Socket Programming

Getting Header Information There are methods that return information extracted from response headers: String getContentType(); String getContentLength(); long getLastModified(); Java Socket Programming

URLConnection Represents the connection (not the URL itself). More control than URL can write to the connection (send POST data). can set request headers. Closely tied to HTTP Java Socket Programming