JAVA Socket Programming 2003.3.19 Joonbok Lee KAIST.

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

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.
2: Application Layer1 Chapter 2 (continued) Application Layer – part 2 Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim.
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.
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,
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.
Welcome to CIS 235 Computer Networks Fall, 2007 Prof Peterson.
2: Application Layer 1 Socket Programming Computer Networking: A Top Down Approach Featuring the Internet, 3 rd edition. Jim Kurose, Keith Ross Addison-Wesley,
2: Application Layer 1 Socket Programming TCP and UDP.
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.
Department of Computer and IT Engineering University of Kurdistan Computer Networks II Socket programming By: Dr. Alireza Abdollahpouri.
 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.
ICT 6621 : Advanced NetworkingKhaled Mahbub, IICT, BUET, 2008 Lecture 10 TCP/IP Application Layer (2)
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.
Lab assignments in Computer Networks at Faculty of Electronic Engineering - Nis.
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.
1 COMP 431 Internet Services & Protocols Client/Server Computing & Socket Programming Jasleen Kaur February 2, 2016.
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.
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.
Socket Programming original by Joonbok Lee KAIST heavily adapted by /Jens.
Topic: Network programming
Socket Programming Socket Programming Overview
Transport layer (last part) Application layer
DNS: Domain Name System
Socket programming with TCP
Chapter 2: outline 2.1 principles of network applications
Socket programming - Java
Socket Programming Socket Programming Overview
Socket Programming.
CSCD 330 Network Programming
Java Socket 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 Joonbok Lee KAIST

What is a socket? Socket –The combination of an IP address and a port number. (RFC 793,original TCP specification) –The name of the Berkeley-derived application programming interfaces (APIs) for applications using TCP/IP protocols. –Two types Stream socket : reliable two-way connected communication streams Datagram socket Socket pair –Specified the two end points that uniquely identifies each TCP connection in an internet. –4-tuple: (client IP address, client port number, server IP address, server port number)

Client-server applications Implementation of a protocol standard defined in an RFC. (FTP, HTTP, SMTP…) –Conform to the rules dictated by the RFC. –Should use the port number associated with the protocol. Proprietary client-server application. –A single developer( or team) creates both client and server program. –The developer has complete control. –Must be careful not to use one of the well-known port number defined in the RFCs. * well-known port number : managed by the Internet Assigned Numbers Authority(IANA)

Socket Programming with TCP Figure 2.6-1: Processes communicating through TCP sockets The application developer has the ability to fix a few TCP parameters, such as maximum buffer and maximum segment sizes.

Sockets for server and client Server –Welcoming socket Welcomes some initial contact from a client. –Connection socket Is created at initial contact of client. New socket that is dedicated to the particular client. Client –Client socket Initiate a TCP connection to the server by creating a socket object. (Three-way handshake) Specify the address of the server process, namely, the IP address of the server and the port number of the process.

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)

Sockets Figure 2.6-2: Client socket, welcoming socket and connection socket

Socket-programming using TCP TCP service: reliable byte stream transfer process TCP with buffers, variables socket controlled by application developer controlled by operating system process TCP with buffers, variables socket internet client server socket( ) bind( ) connect( ) socket( ) bind( ) listen( ) accept( ) send( ) recv( ) close( ) recv( ) send( ) TCP conn. request TCP ACK

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) Input stream: sequence of bytes into process output stream: sequence of bytes out of process Client process client TCP socket

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

JAVA TCP Sockets In Package java.net –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. Constructor and Methods –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.

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(); } }

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); }

Socket Programming with UDP 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.

Client/server socket interaction: UDP close clientSocket Server (running on hostid) read reply from clientSocket 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 write reply to serverSocket specifying client host address, port umber

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

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()

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(); } }

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); }

Building a Simple Web Server Handles only one HTTP request Accepts and parses the HTTP request Gets the required file from the server’s file system. Creates an HTTP response message consisting of the requested file preceded by header lines Sends the response directly to the client

WebServer.java import java.io.*; import java.net.*; import java.util.*; class WebServer{ public static void main(String argv[]) throws Exception { String requestMessageLine; String fileName; ServerSocket listenSocket = new ServerSocket(6789); Socket connectionSocket = listenSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());

WebServer.java requestMessageLine = inFromClient.readLine(); StringTokenizer tokenizedLine = new StringTokenizer(requestMessageLine); if (tokenizedLine.nextToken().equals("GET")){ fileName = tokenizedLine.nextToken(); if (fileName.startsWith("/") == true ) fileName = fileName.substring(1); File file = new File(fileName); int numOfBytes = (int) file.length(); FileInputStream inFile = new FileInputStream (fileName); byte[] fileInBytes = new byte[numOfBytes]; inFile.read(fileInBytes);

WebServer.java outToClient.writeBytes("HTTP/ Document Follows\r\n"); if (fileName.endsWith(".jpg")) outToClient.writeBytes("Content-Type: image/jpeg\r\n"); if (fileName.endsWith(".gif")) outToClient.writeBytes("Content-Type: image/gif\r\n"); outToClient.writeBytes("Content-Length: " + numOfBytes + "\r\n"); outToClient.writeBytes("\r\n"); outToClient.write(fileInBytes, 0, numOfBytes); connectionSocket.close(); } else System.out.println("Bad Request Message"); }

Concurrent server Servers need to handle a new connection request while processing previous requests. –Most TCP servers are designed to be concurrent. When a new connection request arrives at a server, the server accepts and invokes a new process to handle the new client.

How to handle the port numbers cosmos% netstat –a –n –f inet Active Internet connections (including servers) Proto Recv-QSend-QLocal AddressForeign Address (state) tcp00*.23*.* LISTEN cosmos% netstat –a –n –f inet ProtoRecv-QSend-QLocal AddressForeign Address (state) tcp ESTABLISHED tcp00*.23*.* LISTEN cosmos% netstat –a –n –f inet ProtoRecv-QSend-QLocal AddressForeign Address (state) tcp ESTABLISHED tcp ESTABLISHED tcp00*.23*.* LISTEN

Socket programming: references C-language tutorial (audio/slides): “Unix Network Programming” (J. Kurose), Java-tutorials: “All About Sockets” (Sun tutorial), sockets.html “Socket Programming in Java: a tutorial,” sockets.html