Programming TCP Sockets

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

Programming TCP Clients Version InetAddress Class An IP address identifies uniquely a host in the internet, which consists of 4 numbers (1 byte.
Prepared By E. Musa Alyaman1 Java Network Programming TCP.
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
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
Programming TCP Clients. InetAddress Class An IP address identifies uniquely a host in the internet, which consists of 4 numbers (1 byte each one) in.
Universidad de Chile - Tupper 2007, Santiago - Fono/Fax: (56 2) cec.uchile.cl Módulo ECI - 11: Fundamentos de Redes de Computadores.
Internet Programming In Java. References Java.sun.com Java552 Many of the programs shown.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Programming TCP Clients. InetAddress Class An IP address identifies uniquely a host in the internet, which consists of 4 numbers (1 byte each one) in.
Programming TCP Clients Version InetAddress Class An IP address identifies uniquely a host in the internet, which consists of 4 numbers (1 byte.
Networking java.net package, which provides support for networking. Its creators have called Java “programming for the Internet.” Socket :- A network socket.
CEG3185 Tutorial 4 Prepared by Zhenxia Zhang Revised by Jiying Zhao (2015w)
NET0183 Networks and Communications Lecture 31 The Socket API 8/25/20091 NET0183 Networks and Communications by Dr Andy Brooks Lecture powerpoints from.
DBI Representation and Management of Data on the Internet.
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.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
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.
CS 11 java track: lecture 6 This week: networking basics Sockets Vectors parsing strings.
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.
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.
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.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
Sockets For Clients Instructors: Fu-Chiung Cheng ( 鄭福炯 ) Associate Professor Computer Science & Engineering Tatung University.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
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.
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.
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.
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.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Network Programming. These days almost all devices.
Network Programming Communication between processes Many approaches:
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
Java 13. Networking public class SumTest {
Object-Orientated Analysis, Design and Programming
Threads in Java Two ways to start a thread
Network Programming in Java CS 1111 Ryan Layer May 3, 2010
Network Programming Introduction
MCA – 405 Elective –I (A) Java Programming & Technology
NETWORK PROGRAMMING CNET 441
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
Network Programming Introduction
I/O Basics.
Sockets and URLs 17-Sep-18.
Java Network Programming
„Networking”.
CSCD 330 Network Programming
Clients and Servers 19-Nov-18.
Clients and Servers 1-Dec-18.
Networking.
Sockets and URLs 3-Dec-18.
CSCD 330 Network Programming
Programming TCP Clients
Clients and Servers 19-Jul-19.
CS18000: Problem Solving and Object-Oriented Programming
Clients and Servers 13-Sep-19.
What happens when many clients want to contact the server at the same time ? The iterative approach consist in “enqueuing” the requests (this is done.
Exceptions and networking
Presentation transcript:

Programming TCP Sockets Version 2007

The TCP Client’s Socket A TCP socket is an abstraction representing one end in a communication link between two programs. When an application wants to send/receive data to/from a TCP/IP network it has to open one A socket is always bound to a port (although sometimes this will be not evident for the programmer, especially if the program is a client one). The port is the way an application identifies a certain socket with the TCP/IP layer A server which runs on a server also opens a socket bound to a certain port and start listening to requests from the clients whishing to establish a communication. In order to establish a TCP/IP communication with a server, a client has to previously know 1- the port number, 2- the host address. With this information the client tries a rendezvous where the server is already running and listening.

TCP Client in Java (1) For trying a rendezvous in Java client we must create an object of the Socket class. Socket(String host, int port) Socket csocket = new Socket(“hostname”,7); A host address can be given as an IP number or name: dichato.dcc.uchile.cl or 192.24.80.40. In the first case Java will do the DNS lookup first. The creation of a socket is a blocking statement. This means that the execution of the program will block until the creation returns a socket connected to the server or a null if it fails. A failure to create a socket may arise if there is no such host in the internet, if the host is not currently reachable, or if there is no server listening to that port on that host. There is a timeout (default) for this instruction. A failure will throw a checked Exception. It is therefore necessary to program the socket creation within a try-and- catch block

TCP Client in Java (2) After the socket is created we can open an InputStream and an OuputStream from that socket in order to read data from an write data into the server. PrintWriter out = new PrintWriter( csocket.getOutputStream(), true); BufferedReader In = new BufferedReader(new InputStreamReader(csocket.getInputStream())); Both getInputStream & getOutputStream open byte oriented data streams. Printwriter & BufferedReader are “filters” which convert bytes into text (string with end-of-line marks) and vice-versa. out.print(“hello”); out.println(“how are you ?”); String linea = in.readLine(); readLine is a blocking sentence. For using it we must be sure the server will send an eol mark.

A Client for the date server Protocol: The date server just waits until someone tries a rendezvous and answers with the current date of the server. This means the client must try rendezvous (1) and then read the response of the server (2). Then the server breaks the communication. No data can be read anymore (the result would be null). 2- read data Client Date server 1- connect 13 DateClient URLs of time servers

import java.io.*; import java.net.*; public class DateClient { public static void main(String[] args) throws Exception { dateSocket = new Socket(args[0],PORT); //opening a text-oriented input channel in = new BufferedReader(new InputStreamReader(dateSocket.getInputStream())); //read data from server String line = in.readLine(); //print on the screen System.out.println("date received: " + line); //close socket and everything attached to it dateSocket.close(); }

The Sockets constructors Socket(String host, int port) The port must be in the range 1-65,535 Socket(InetAddress host, int port)The same but with an InetAddress object as parameter Socket(String host, int port, InetAddress localHost, int localport) Every TCP communication consists of a local and remote host and a local and remote port. This constructor allows us to specify all them. Specifying local address makes only sense when local computer is multihomed (more than one address). If null is given, default address is used. Sometimes it is necessary to specify the local port (firewalls). If 0 is given the system will assign a random available port number. Numbers from 1 to 1025 should not be used as they are reserved for “well known services” like echo, telnet finger, ftp.

More Socket methods in Java InetAddress getInetAddress() returns the IP address of the remote host to which the socket is connected int getPort() returns the port number to which the socket at the other extreme is bound InetAddress getLocalAddress() returns the IP address of the local host int getLocalPort() returns the port number to to which the socket is bound. void setSoTimeout(int timeout)sets timeout in milliseconds for a read operation on this socket. 0 = no timeout, this can block the operation indefinitely. If the reading operation is not completed in that time an InterruptedIOException is thrown int getSoTimeout() returns the timeout of the socket

More Socket methods in Java void setTcpNoDelay(boolean on) Disables/Enables using the Nagel’s algorithm which makes TCP more efficient by delaying the writing (sending) of small amounts of data until there is enough data to send. This may introduce some unacceptable delays for some applications. boolean getTcpNoDelay() returns whether the Nagel’s algorithm is working or not void setSoLinger(boolean on, int val) allows to set a linger time-out (in milliseconds). Linger is the time the socket communication remains “open” by the system after the program closes it. This will allow to receive packages for confirmation which are still delayed and avoid the using of the same port on the same machine for some 4 min. int getSoLinger () returns the current linger setting or –1 if not set. void setSendBufferSize(int size) int getSendBufferSize() void setReceiveBufferSize(int size) int getReceiveBufferSize()

Socket originated Exceptions Many of the Socket constructors and methods throw a checked exception, mostly from a type extended from IOException. These instructions should be programmed inside a try-and-catch block Most of the thrown exceptions are objects from a subclass of the IOException class BindException: the requested local port or address could not be used. Typically when the port is already used or it is a system port or the local address is not a valid one. ConnectException: connection refused because there was no server listening to that port on the remote host. NoRouteToHostException: remote host could not be reached typically because of network problems or a firewall UnknownHostException: the given host address is not valid (DNS Lookup filed)

Programming the Server What happens on the server when the client tries to establish a rendezvous ? The server starts listening to requests on a ServerSocket After accepting the request the resulting connection is attached to another (normal) socket (same type as client’s socket)

Sockets at the Server Side (1) The server should start by creating a server socket bound to a certain port according to the protocol of the service. ServerSocket listening; listening = new ServerSocket(5555); (or ServerSocket(portnumber, queueLength) This will create the socket but the server is still not listening. To do this we should apply the following method to the socket: Socket toClient = listening.accept(); This sentence works the following way: accept blocks the execution of the program until there is a petition for a connection from a client executing the instruction calling = new Socket(host, 5555); When the requirement arrives, a TCP connection is established between the two computers. The client receives in its socket one end of this link and the server the other.

Sockets at the Server Side(2) At the server side we can apply the same methods as we did at the client side. Particularly we may need to open an input and an output data stream. After this, the server should implement the protocol. It is important that both side follow this protocol in order not to block the communication and/or miss some data. This mean following the “turn taking” rules of sending to and receiving data and the format of the data to be exchanged. Note that the server socket (and port) at which the server was originally listening to requests is not used anymore. This is a design issue

A Date Server We will program now a date server for a computer which has no one 1) answer with the date in another socket 2) close the connection Client Date server 13 a) Create the server socket b) start listening

import java.net.*; import java.io.*; import java.util.*; public class DateServer { public static void main(String args[]) throws Exception { //If I don't want to care about exception I put throws Exception //create a server socket bound to the port passed as parameter ServerSocket server = new ServerSocket(Integer.parseInt(args[0])); while(true) { System.out.println("Waiting for client..."); Socket client = server.accept(); System.out.println("Accepted from "+client.getInetAddress()); PrintWriter bo = new PrintWriter(client.getOutputStream(),true); //creating a date objrct with the System's date Date d = new Date(); // sending bo.println(d.toString()); }

Downloading files 2) Input filename from keyboard 1) Connect 3) Send filename 4) Send bytes 5) Write bytes 3) Read bytes Repeat 3,4,5 until all the file is transmitted ArchServidor.java ArchCliente.java This file server is very unstable !!!

import java.io.*; import java.net.*; public class ArchServidor { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(666); while(true) { cs = ss.accept(); BufferedReader inSocket = new BufferedReader( new InputStreamReader(cs.getInputStream())); String fileName = inSocket.readLine(); FileInputStream inFile = new FileInputStream(fileName); OutputStream outSocket = cs.getOutputStream(); int b; byte ab[] = new byte[1024]; while ((b= inFile.read(ab,0,1024) ) != -1) { outSocket.write(ab,0,b); }

import java.io.*; import java.net.*; public class ArchCliente { public static void main(String[] args) throws Exception { Socket elSocket = null; elSocket = new Socket(args[0], 4449); PrintWriter outSocket = new PrintWriter(elSocket.getOutputStream(),true); outSocket.println(args[1]); FileOutputStream outFile = new FileOutputStream(fileName); InputStream inSocket = elSocket.getInputStream(); int b; byte ab[] = new byte[1024]; while ((b= inSocket.read(ab,0,1024) ) != -1) outFile.write(ab,0,b); }