1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Lecture 10: Networking using Socket Programming. Client-Server Model b The term server applies to any program that offers a service that can be reached.
COMP201 Java Programming Part III: Advanced Features Topic 14: Networking Volume II,Chapter 3.
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.
Socket Programming.
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.
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 Overview r Socket programming with TCP r Socket programming with UDP r Building a Web server.
Java Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated.
COMP1681 / SE15 Introduction to Programming
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
© Lethbridge/Laganière 2001 Chap. 3: Basing Development on Reusable Technology 1 Let’s get started. Let’s start by selecting an architecture from among.
2: Application Layer1 Socket Programming. 2: Application Layer2 Socket-programming using TCP Socket: a door between application process and end- end-transport.
Welcome to CIS 235 Computer Networks Fall, 2007 Prof Peterson.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
TCP Sockets Reliable Communication. TCP As mentioned before, TCP sits on top of other layers (IP, hardware) and implements Reliability In-order delivery.
2: Application Layer 1 Socket Programming TCP and UDP.
EE2E1. JAVA Programming Lecture 9 Network Programming.
Greg Jernegan Brandon Simmons. The Beginning…  The problem Huge demand for internet enabled applications and programs that communicate over a network.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
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.
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of 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.
DBI Representation and Management of Data on the Internet.
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
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Socket Programming Tutorial. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
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.
© Lethbridge/Laganière 2005 Chap. 3: Basing Development on Reusable Technology The Client-Server Architecture A distributed system is a system in.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
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.
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,
VII. Sockets. 1. What is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes.
Part 4: Network Applications Client-server interaction, example applications.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
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.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Prepared by Dr. Jiying Zhao University of Ottawa Canada.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
1 COMP 431 Internet Services & Protocols Client/Server Computing & Socket Programming Jasleen Kaur February 2, 2016.
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.
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
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.
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.
Java Networking I IS Outline  Quiz #3  Network architecture  Protocols  Sockets  Server Sockets  Multi-threaded Servers.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 11 Omar Meqdadi Department of Computer Science and Software Engineering University.
SOCKET PROGRAMMING WITH JAVA By Collin Donaldson.
Network Programming. These days almost all devices.
Network Programming Communication between processes Many approaches:
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
MCA – 405 Elective –I (A) Java Programming & Technology
Client-Server Interaction
CSCD 330 Network Programming
Chapter 2: outline 2.1 principles of network applications
Socket programming - Java
Distributed Computing
Chapter 2: Application layer
Presentation transcript:

1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University

2 TCP/IP Stack Application In this chapter TCP IP

3 Introduction  Internet protocols (TCP/IP) provide –General-purpose facility for reliable data transfer –Mechanism for contacting hosts  Application programs –Use internet protocols to contact other applications –Provide user-level services  Application-level protocols provide high-level services –DNS –Electronic mail –Remote login –FTP –World Wide Web  All of these applications use client-server architecture

4 Client-Server Paradigm  Server application is "listener" –Waits for incoming message –Performs service –Returns results –Examples: »Web server »FTP server  Client application establishes connection –Sends message to server –Waits for return message –Examples: »Web Browser »FTP client tools »FTP command line interface, etc.

5 Transport Protocols  Clients and servers exchange messages through transport protocols; e.g., TCP or UDP  Both client and server must have same protocol stack and both interact with transport layer  Can have multiple Servers on the same machine

6 Identifying Sessions  How do incoming messages get delivered to the correct server? –Unique address to identify the machine (IP address) –TCP or UDP protocol port numbers can be used to identifier multiple servers on same machine. –Servers listens to a predetermined port  Each transport session has two unique identifiers –(IP address, port number) on server –(IP address, port number) on client  No two clients on one computer can use same source port –Client end-end points (client IP Address, port number) are unique  sessions are unique

7 Network Servers  Servers continuously running on machines waiting (listening) for connection requests.  Servers usually listen for a particular port on the machine they are running on.  Ports enable us run many servers on the same machine  Sample server ports (): –day time 13 –FTP 21 –SMTP 25 –who is 43 –login 513 –http 80  Check /etc/services file on Unix and netstat –an on Windows –Check for more infohttp://  Can have your own servers running on a port other than already used ports -- avoid standard ports numbers < 1024

8 “Netstat” output C:\>netstat –an Active Connections Proto Local Address Foreign Address State TCP : :0 LISTENING TCP : :0 LISTENING TCP : :0 LISTENING TCP : :0 LISTENING TCP : :0 LISTENING TCP : :0 LISTENING UDP :427 *:* UDP :445 *:* UDP :500 *:* UDP :1026 *:* UDP :1036 *:* UDP :1063 *:* UDP :2812 *:* UDP :4500 *:* UDP :38037 *:* UDP :123 *:* UDP :1900 *:* UDP :3200 *:* UDP :123 *:* UDP :137 *:* UDP :138 *:* UDP :1900 *:* C:\>

9 Telnet to Debug Servers  telnet host port-number  Try this: –Get time of day on stallion: »telnet 13 »telnet nist1.datum.com 13 ( ) –Get QU home page »telnet 80 »get –Send an using an SMTP server »telnet mail.qu.edu.qa 25 »follow sendmail protocol

10 Protocol Example (SMTP) >>>Telnet mail.yahoo.com ESMTP mail.yahoo.com Sendmail SGI.8.8.8/ SGI.AUTOCF ready at Wed, 31 Jan :49: (CST) >>>HELO qmpc 250 mail.yahoo.com Hello [ ], pleased to meet you >>>MAIL FROM: 250 Sender ok >>>RCPT TO: 250 Recipient ok >>DATA 354 Enter mail, end with "." on a line by itself This is my message You got it. SMTP is simple. 250 RAA06347 Message accepted for delivery >>>Quit

11 Socket Connections  Import java.net package  Many things can go wrong over the network -- Use try/Catch block  Open a socket Socket s = new Socket(” 13);  Get input stream on the socket InputStream in = s.getInputStream();  Once you have grabbed the stream, you can read from it  Close() closes the socket Host Name or IP address Port number

12 Steps for Reading and Writing to Sockets 1. Open a socket. 2. Open an input stream and output stream to the socket. 3. Read from and write to the stream according to the server's protocol. 4. Close the streams. 5. Close the socket. Only step 3 differs from client to client, depending on the server. The other steps remain largely the same

13 Example: Socket Connection import java.io.*; import java.net.*; public class SocketTest { public static void main(String[] args) { try { Socket s = new Socket("time-A.timefreq.bldrdoc.gov", 13); BufferedReader in = new BufferedReader (new InputStreamReader(s.getInputStream())); boolean more = true; while (more) { String line = in.readLine(); if (line == null) more = false; else System.out.println(line); } catch (IOException e) { System.out.println("Error" + e); }

14 Network Servers  Every server program (http, smtp, ftp, etc.) continues to execute the following loop: –wait listening to a socket –get command from client through an incoming data stream associated with that socket –fetch and process information –send information back to client through an outgoing data stream Client Server request reply Input steam Output stream

15  The server program begins by creating a new ServerSocket object to listen on a specific port try { serverSocket = new ServerSocket(8587); } catch (IOException e) {... }  Using the accept method, server waits (blocks indefinitely) listening for a client connection requests on the port of this server – accept returns a socket object Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) {...} Creating Java server (1)

16  Server communicates with the client: –Gets the socket's input and output stream and opens readers and writers on them. »Get I/O objects for communication  OutputStream - sends info to client  InputStream - gets info from client u Server's input stream is client's output stream, and vice versa »Use Socket object to get references to streams u clientSocket.getInputStream() u clientSocket.getOutputStream() –May construct the proper I/O stream, reader, or writer depending on the Client-Server protocol – See later slides –Server communicates with the client by reading from and writing to the socket using the captured streams. »Methods write(), read(), readLine(), print(), etc. Creating Java Server (2)

17  Housekeeping by closing all of the input and output streams, client socket, and server socket: out.close(); in.close(); clientSocket.close(); serverSocket.close();  Notice that networking appears as sequential file I/O –Sockets simplify networking Creating Java Server (3)

18 Example: Echo Server import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args ) { try { ServerSocket s = new ServerSocket(8189); Socket incoming = s.accept( ); BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); boolean done = false; while (!done) { String line = in.readLine(); if (line == null) done = true; else { out.println("Echo: " + line); if (line.trim().equals("BYE")) done = true; } incoming.close(); } catch (Exception e) { System.out.println(e); }

19 Threaded Servers  For handling multiple clients – use a thread for handling each client. while (true) { accept a connection ; create a thread to deal with the client ; } //end while

20 Example: Threaded Echo Server (1) import java.io.*; import java.net.*; public class ThreadedEchoServer { public static void main(String[] args ) { int i = 1; try { ServerSocket s = new ServerSocket(8189); for (;;) { Socket incoming = s.accept( ); System.out.println("Spawning " + i); new ThreadedEchoHandler(incoming, i).start(); i++; } catch (Exception e) { System.out.println(e); }

21 Example: Threaded Echo Server (2) class ThreadedEchoHandler extends Thread { public ThreadedEchoHandler(Socket i, int c) { incoming = i; counter = c; } public void run() { try { BufferedReader in = new BufferedReader (new InputStreamReader(incoming.getInputStream())); PrintWriter out = new PrintWriter (incoming.getOutputStream(), true /* autoFlush */); out.println( "Hello! Enter BYE to exit." ); boolean done = false; while (!done) { String str = in.readLine(); if (str == null) done = true; else { out.println("Echo (" + counter + "): " + str); if (str.trim().equals("BYE")) done = true; } incoming.close(); } catch (Exception e) { System.out.println(e); } private Socket incoming; private int counter; }

22 Using Stream I/O Classes  For transmitting text –readLine() of BufferedReader –print() and println() of PrintWriter  Binary data –DataInputStream –DataOutputStream BufferedReader in = new BufferedReader (new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter (socket.getOutputStream(), true /* autoFlush */); DataInputStream in = (new DataInputStream(socket.getInputStream())); DataOutputStream out = (new DataOutputStream(socket.getOutputStream()));

23  Create Socket to connect to server Socket connection = new Socket(serverAddress, port) –If successful, returns Socket. May throw a subclass of IOException  Get stream objects –connection.getInputStream() –connection.getOutputStream() –Use captured streams to create proper stream types for Client-Server protocol  Processing phase -- Communicate using stream objects  Termination –Transmission complete –connection.close() (close Socket )  Client must determine when server done –read blocks until input data is available, the end of the stream is detected, or an exception is thrown – May throw a subclass of IOException –read returns -1 when eof found –For some InputStream s read May generates EOFException Creating Java Client

24 Internet Addresses  Internetworked machines have names ( and IP addresses ( )  Host may have multiple IP addresses  Can use InetAddress class to convert between the two. –static InetAddress getByName(String host) –static InetAddress[] getAllByName(String host) –static InetAddress getLocalHost() –String getHostAddress() Returns the IP address string "%d.%d.%d.%d”. –String getHostName() Gets the host name for local machine. For more details check

25 Client import java.net.*; import java.io.*; public class MailTest { PrintWriter out; BufferedReader in; public static void main(String[] args ) { MailTest T = new MailTest(); T.send (); } public void send () { try { Socket s = new Socket(" ", 25); out = new PrintWriter(s.getOutputStream()); in = new BufferedReader(new InputStreamReader(s.getInputStream())); String hostName = InetAddress.getLocalHost().getHostName(); send(null); send("HELO " + hostName); send("MAIL FROM: " + send("RCPT TO: " + send("DATA"); out.println("This is a test "); send("."); s.close(); } catch (IOException exception) { System.out.println("Error: " + exception); } } public void send(String s) throws IOException { if (s != null) { out.println(s); out.flush(); } String line; if ((line = in.readLine()) != null) System.out.println("I Recieved: "+line +"\n"); }