1 / 152

Network Programming lab(java)

This PPT is Dedicated to my inner controller AMMA BHAGAVAN – ONENESS Founders. Developed by, EDITED BY, S.V.G.REDDY, M.Siva Naga Prasad Associate professor, student of M.tech(SE). Dept.of CSE, GIT, GITAM UNIVERSITY. Network Programming lab(java). WELL KNOWN PORTS.

etana
Télécharger la présentation

Network Programming lab(java)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. This PPT is Dedicated to my inner controller AMMA BHAGAVAN– ONENESS Founders. Developed by, EDITED BY, S.V.G.REDDY, M.Siva Naga Prasad Associate professor, student of M.tech(SE). Dept.of CSE, GIT, GITAM UNIVERSITY. Network Programming lab(java)

  2. WELL KNOWN PORTS

  3. Program: import java.io.*; import java.net.*; class wkports { public static void main(String args[]) { for(int i=100;i<200;i++) { try { Socket s=new Socket(host,i); System.out.println("There is a server on port :"+ i +" of: " +host); } catch(UnknownHostException e) { System.err.println(e); } catch(IOException ie) { System.out.println(ie.getMessage()); } } } }

  4. Output:-

  5. One to One Chat Application

  6. One-to-one communication is the act of an individual communicating with another. • In Internet terms, this can be done by e-mail but the most typical one-to-one communication in the Internet is instant • messaging as it does not consider many-to-many communication such as a chat room as an essential part of its scope

  7. The program displays what is written by one party to another by opening a socket connection • The Application contains two classes: • 1.Chat client • 2.Chat server • The chat server class creates class creates a serves socket object which listens on port 9999.The server socket accepts client socket and reads whatever is written by client and sends the message to the client thus allowing One-one communication • The Chat client class creates a socket object using which it sends message to the server on port 9999.The communication ends when the client send server says “bye”. Description

  8. Socket Programming Exception Handling I/O and StreamClasses Topics Included in This…….

  9. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and Server Socket--that implement the client side of the connection and the server side of the connection, respectively. Socket Programming:

  10. What is Exception??? • An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Why Exception Handling?? • To terminate the program neatly in error condition or unexpected scenario. • To fix the problem at run time • To give user friendly messages to end user in case of unusual scenario or error Exception Handling:

  11. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the runtime system is called throwing an exception. In java Exception handling is achieved by using Try , Catch and Finally Blocks of code. The Super class for all types of exceptions in java is java.lang.Exception Exception Handling Using Java:

  12. try { code } CATCH BLOCK catch (Exception ex) { <do something with ex> } • catch • A method can catch an exception by providing an exception handler for that type of exception. Try Block

  13. Client side program: import java.io.*; import java.net.*; import java.lang.*; public class chatclient1 { public static void main(String args[]) throws IOException { Socket csoc=null; String host; if(args.length>0) host=args[0]; else host="localhost"; PrintWriter pout=null; BufferedReader bin=null; try { csoc=new Socket(host,7); pout=new PrintWriter(csoc.getOutputStream(),true); bin=new BufferedReader(new InputStreamReader(csoc.getInputStream())); }

  14. catch(UnknownHostException e) { System.err.println("Unknownhost"); System.exit(1); } catch(IOException e) {} BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); String input; while(true) { input=in.readLine(); pout.println(input); String msg=bin.readLine(); System.out.println("client :"+msg); if(msg.equals("bye")) break; } in.close(); pout.close(); bin.close(); csoc.close(); } }

  15. Server side program: import java.io.*; import java.net.*; import java.lang.*; public class chatserver1 { public static void main(String args[]) throws IOException { ServerSocket ssoc=null; try { ssoc=new ServerSocket(7); } catch(IOException e) { System.err.println("No connection established"); System.exit(1); } Socket csoc=null; try { csoc=ssoc.accept(); }

  16. catch(IOException e) { System.err.println("Not accepted"); System.exit(1); } PrintWriter pw=new PrintWriter(csoc.getOutputStream(),true); BufferedReader br=new BufferedReader(new InputStreamReader(csoc.getInputStream())); String inline; String outline; try { DataInputStream din=new DataInputStream(System.in); while(true) { inline=br.readLine(); System.out.println("Server :"+inline); outline=din.readLine(); pw.println(outline); if(outline.equals("bye")) break; } }

  17. catch(Exception e) { System.err.println(e); } pw.close(); br.close(); csoc.close(); ssoc.close(); } }

  18. Server side output window: Clint side output window:

  19. Many to Many Chat Application

  20. Each client opens a socket connection to the chat server and writes to the socket whatever is written by one party can be seen by all other parties. Chat Rooms in yahoo is the best example for this many to many chat application. Description:

  21. Connections Between Systems

  22. Socket communication Exception Handling IO Multi Threading Concepts Behind This

  23. A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes are used to represent the connection between a client program and a server program. The java.net package provides two classes--Socket and Server Socket--that implement the client side of the connection and the server side of the connection, respectively. Socket Programming

  24. It Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines • It belongs to java.io Package. • BufferedReader(Readerin)           Create a buffering character-input stream that uses a default-sized input buffer. • Methods In This Class… ReadLine(): Read a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed Classes in this program:

  25. Print Writer: • Print formatted representations of objects to a text-output stream. • public PrintWriter(OutputStreamout,booleanautoFlush) Create a new PrintWriter from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

  26. InputStream Returns an input stream for socket. This method is Belongs socket class. Socket class is belongs to java.net. Package OutPutStream Returns an output stream for socket. Get Input/output Stream

  27. An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset. The charset that it uses may be specified by name or may be given explicitly, or the platform's default charset may be accepted. • Public InputStreamReader(InputStream in) : Create an InputStreamReader that uses the default charset. Input Stream Reader

  28. A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream. • public DataInputStream(InputStream in) : Creates a DataInputStream that uses the specified underlying InputStream DataInputStream

  29. Thread is a Active part of execution. • Thread is a path of execution. • Threads are also called as lightweight process • Threads are executed in parallel. Multi Threading

  30. We can implement multi threading using java in 2 ways 1.)By inheriting Thread class or 2.)By Implementing RUNNABLE interface Multithreading using java

  31. To implement Multi threading we have to override the run method of Thread class Thread class is belongs to java.lang. package Methods in this class Start(),run(),sleep(),stop(),join()…e.t.c. Thread Class

  32. This is an interface with only one method That is RUN() By implementing this interface we can get multi threading Runnable Interface

  33. CLIENT SIDE PROGRAM : import java.net.*; import java.io.*; public class mclient { public static void main(String a[]) { BufferedReader in; PrintWriter pw; try { Socket s = new Socket("localhost",118); System.out.println("Enter name"); in = new BufferedReader(new InputStreamReader(System.in)); String msg = in.readLine(); pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream())); pw.println(msg+"\n"); pw.flush(); while(true) { readdata rd = new readdata(s); Thread t = new Thread(rd); t.start();

  34. msg = in.readLine(); if(msg.equals("quit")) { System.exit(0); } pw.println(msg); pw.flush(); } } catch(Exception e) { System.out.println(e); } } } class readdata implements Runnable { public Socket s; public readdata(Socket s) { this.s = s; }

  35. public void run() { BufferedReader br; try { while(true) { br = new BufferedReader(new InputStreamReader(s.getInputStream())); String msg = br.readLine(); System.out.println(msg); } } catch(Exception e) { System.out.println(e); } } }

  36. SERVER SIDE PROGRAM : import java.net.*; import java.io.*; public class mserver { public static Socket s[] = new Socket[10]; public static String user[] = new String[10]; public static int total; public static void main(String a[]) { int i=0; try { ServerSocket ss = new ServerSocket(118); while(true) { s[i] = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s[i].getInputStream())); String msg = br.readLine(); user[i] = msg;

  37. System.out.println(msg+" connected") ; try { reqhandler req = new reqhandler(s[i],i); total = i; i++; Thread t = new Thread(req); t.start(); } catch(Exception e) { System.out.println(e); } } } catch(Exception e) { System.out.println(e); } } }

  38. class reqhandler implements Runnable { public int n; public Socket s; public reqhandler(Socket soc,int i) { s = soc; n = i; } public void run() { String msg = ""; BufferedReader br,br1; PrintWriter pw; try { while(true) { br1 = new BufferedReader(new InputStreamReader(System.in)); if((br1.readLine()).equals("quit")) System.exit(0); br = new BufferedReader(new InputStreamReader(s.getInputStream())); msg = br.readLine(); i

  39. if(msg.equals("quit")) mserver.total--; else System.out.println(mserver.user[n]+"->"+msg); if(mserver.total == -1) { System.out.println("Server Disconnected"); System.exit(0); } for(int k=0;k<=mserver.total;k++) if(!mserver.user[k].equals(mserver.user[n])&&(!msg.equals("quit"))) { pw = new PrintWriter(new OutputStreamWriter(mserver.s[k].getOutputStream())); pw.println(mserver.user[n]+":"+msg+"\n"); pw.flush(); } } } } catch(Exception e) { } } }

  40. OUTPUT:

  41. Output:

  42. Data Retrieval from a remote Database

  43. Server 1. Request for data from database 2. Access to data base Give response to client Data base Client

  44. Server Server side program: • Listening to the port, • Establishing connections • Reading from and writing to the socket.

  45. A socket is an end point for communication between two machines Server ServerSocket ssoc=new ServerSocket(1111); This ServerSocket object is used to listen on a port

  46. Port is an address that identifies the particular application in destination machine 192.256.17.25 Port: 1111

  47. Establishing connections Server Accepting the connection Client Socket csoc=ssoc.accept(); Client socket object which is bound to same local port(1111) The communication is done through the new socket object

  48. In Server program: BufferedReader fromc= new BufferedReader(new InputStreamReader(csoc.getInputStream())) csoc.getInputStream: It reads input from socket object PrintStream toc=new PrintStream(csoc.getOutputStream()); csoc.getOutputStream: It writes stream of data to socket object

  49. In client program: PrintStream tos=new PrintStream(soc.getOutputStream()); It writes stream of data to socket object BufferedReader froms=new BufferedReader(new InputStreamReader(soc.getInputStream())); It reads input from socket object BufferedReader fromkb=new BufferedReader(new InputStreamReader(System.in)); Takes the input from keyboard

More Related