Vous êtes sur la page 1sur 22

UNIT-2 Networking Lecture-5 Topics: (1) Basic Concepts on Networking IP Address Protocol Ports The Client/Server Paradigm -Sockets

kets (2)Connecting to a server

(1)Basic Concept on Networking: The Internet: A global network of computers connected together in various ways Remains functional despite of diversity of hardware and software connected together Possible through communication standards defined and conformed to Guarantee compatibility and reliability of communication IP Address: Logically similar to the traditional mailing address. An address uniquely identifies a particular object. Each computer connected to the Internet has a unique IP address. A 32-bit number used to uniquely identify each computer connected to the Internet 192.1.1.1 docs.rinet.ru
Protocol: Why protocols?

Different types of communication occurring over the internet. Each type of communication requires a specific and unique protocol. Definition: - Set of rules and standards that define a certain type of Internet communication Describes the following information:

- Social protocol used in a telephone conversation Gives us confidence and familiarity of knowing what to do. Some important protocols used over the Internet Hypertext Transfer Protocol (HTTP) Used to transfer HTML documents on the Web File Transfer Protocol (FTP) More general compared to HTTP Allows you to transfer binary files over the Internet Both protocols have their own set of rules and standards on how data is tansferred Java provides support for both protocols Port: Protocols only make sense when used in the context of a service HTTP protocol is used when you are providing Web content through an HTTP service Each computer on the Internet can provide a variety. of services. Why Ports? The type of service must be known before information can be transferred. Definition: A 16-bit number that identifies each service offered by a network server. Using a particular service to establish a line of communication through a specific protocol. Need to connect to the appropriate port. Standard ports Numbers specifically associated with a particular type of service Examples: The FTP service is located on port 21 The HTTP service is located on port 80 Given port values below 1024 Port values above 1024 Available for custom communication

The Client/Server paradigm: Basis for Java networking framework Involves two major elements: Client Machine in need of some type of information Server Machine storing information and waiting to give it out. Scenario: Client connects to a server and queries for certain

Socket: Definitions: Software abstraction for an input or output medium of communication Communication channels that enable you to transfer data through a particular port - An endpoint for communication between two machines A particular type of network communication used in most Java network programming Java performs all of its low-level network communication through sockets

Java Networking Package: The java.net package Provides classes useful for developing networking applications Some classes in the package: - ServerSocket Socket MulticastSocket DatagramPacket Server Socket Class: Provides the basic functionalities of a server Has four constructors

Server Socket Class:Method:

Server Socket Class Example: 1import java.net.*; 2 import java.io.*; 3 public class EchoingServer { 4 public static void main(String [] args) { 5 ServerSocket server = null; 6 Socket client; 7 try { 8 server = new ServerSocket(1234); 9 //1234 is an unused port number 10 } catch (IOException ie) { 11 System.out.println("Cannot open socket."); 12 System.exit(1); 13 } 14 Contineued while(true) { 16 try { 17 client = server.accept(); 18 OutputStream clientOut = 19 client.getOutputStream(); 20 PrintWriter pw = new PrintWriter(clientOut, true); 22 InputStream clientIn = 23 client.getInputStream(); 24 BufferedReader br = new BufferedReader(new 25 InputStreamReader(clientIn)); 26 pw.println(br.readLine()); 27 } catch (IOException ie) {}}}

(2)Connecting to a server: Here file name is Greeting Client that connect to a server by using a socket. Example: import java.net.*; import java.io.*; public class GreetingClient { public static void main(String [] args) { String serverName = args[0]; int port = Integer.parseInt(args[1]); try { System.out.println("Connecting to " + serverName + " on port " + port); Socket client = new Socket (serverName, port); System.out.println("Just connected to " + client.getRemoteSocketAddress()); OutputStream outToServer = client.getOutputStream(); DataOutputStream out = new DataOutputStream(outToServer); out.writeUTF("Hello from " + client.getLocalSocketAddress()); InputStream inFromServer = client.getInputStream(); DataInputStream in = new DataInputStream(inFromServer); System.out.println("Server says " + in.readUTF()); client.close(); } catch(IOException e) { e.printStackTrace(); } } }

Lecture -6 Topics: Java Socket Implementing Server Implementing Client. Sending Email.

Java Socket:

Java Sockets
Server

ServerSocket(1234)

Output/write stream Input/read stream

Client

Socket(128.250.25.158, 1234) It can be host_name like mandroo.cs.mu.oz.au 17

Implementing a server:

1.Open the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); 2. Wait for the Client Request:

Socket client = server.accept(); 3. Create I/O streams for communicating to the client is = new DataInputStream( client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 4. Perform communication with client Receive from client: String line = is.readLine(); Send to client: os.writeBytes("Hello\n"); 5. Close sockets: client.close(); For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with client socket as parameter (the thread creates streams (as in step3 and does communication as stated in (4). Remove thread once service is provided. }

Implementing Client: 1. Create a Socket Object: client = new Socket( server, port_id ); 2. Create I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getOutputStream() ); 3. Perform I/O or communication with the server: Receive data from the server: String line = is.readLine(); Send data to the server: os.writeBytes("Hello\n"); 4. Close the socket when done: client.close();

Example of Server: import java.net.*; import java.io.*; public class SimpleServer { public static void main(String args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); Socket s1=s.accept(); // Wait and accept a connection

// Get a communication stream associated with the socket OutputStream s1out = s1.getOutputStream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeUTF("Hi there"); // Close the connection, but not the server socket dos.close(); s1out.close(); s1.close(); } }

Example of Client: import java.net.*; import java.io.*; public class SimpleClient { public static void main(String args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket("mundroo.cs.mu.oz.au",1234); // Get an input file handle from the socket and read the input InputStream s1In = s1.getInputStream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readUTF()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1In.close(); s1.close(); }

Sending Email: import java.util.*; import javax.mail.*; import javax.mail.internet.*; import javax.activation.*; public class SendEmail { public static void main(String [] args) { // Recipient's email ID needs to be mentioned. String to = "abcd@gmail.com"; // Sender's email ID needs to be mentioned String from = "web@gmail.com"; Assuming you are sending email from localhost String host = "localhost"; // Get system properties Properties properties = System.getProperties(); // Setup mail server properties.setProperty("mail.smtp.host", host); // Get the default Session object. Session session = Session.getDefaultInstance(properties); try{ // Create a default MimeMessage object. MimeMessage message = new MimeMessage(session); // Set From: header field of the header. message.setFrom(new InternetAddress(from)); //Set To: header field of the header. message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Set Subject: header field message.setSubject("This is the Subject Line!"); // Now set the actual message message.setText("This is actual message");

// Send message Transport.send(message); System.out.println("Sent message successfully...."); }catch (MessagingException mex) { mex.printStackTrace(); } } }

Lecture-7 Topic: URL Url Connections Reading URL connection Writing URL connection.

URL: Uniform Resource Locator (URL) is a Uniform Resource Identifier (URI) that specifies
where an identified resource is available and the mechanism for retrieving it.

Url Connection. If you've successfully used openConnection() to initiate communications with a URL, then you have a reference to a URLConnection object. The URLConnection class contains many methods that let you communicate with the URL over the network. URLConnection is an HTTP-centric class--many of its methods are useful only when working with HTTP URLs. However, most URL protocols let you read from and write to the connection so this page shows you how to both read from and write to a URL through a URLConnection object.

Reading from a URLConnection The following program performs the same function as the program shown in Reading Directly from a URL. However, rather than opening a stream directly from the URL, this program explicitly opens a connection to the URL, gets an input stream on the connection, and reads from the input stream: import java.net.*; import java.io.*; class ConnectionTest { public static void main(String[] args) { try { URL yahoo = new URL("http://www.yahoo.com/"); URLConnection yahooConnection = yahoo.openConnection(); DataInputStream dis = new DataInputStream(yahooConnection.getInputStream()); String inputLine; while ((inputLine = dis.readLine()) != null) { System.out.println(inputLine);

} dis.close(); } catch (MalformedURLException me) { System.out.println("MalformedURLException: " + me); } catch (IOException ioe) { System.out.println("IOException: " + ioe); } } }

Writing to a URLConnection Many HTML pages contain forms--text fields and other GUI objects that let you enter data to the server. After you type in the required information and initiate the query by clicking on a button, the Web browser you're using writes the data to the URL over the network. At the other end, a (usually) cgi-bin script on the server the data, processes it, and then sends you back a response, usually in the shape of a new HTML page. This scenario is often used to support searching. Many cgi-bin scripts use the POST METHOD for reading the data from the client. Thus writing to a URL is often known as posting to a URL. Server-side scripts that use the POST METHOD read from their standard input.

Java programs can also interact with cgi-bin scripts on the server-side. They simply must be able to write to a URL, thus providing data to the server. Your program can do this by following these steps: 1. Create a URL. 2. Open a connection to the URL. 3. Get an output stream from the connection. This output stream is connected to the standard input stream of the cgi-bin script on the server. 4. Write to the output stream. 5. Close the output stream. 6. Here's an example program that runs the backwards script over the network through a URLConnection: import java.io.*; import java.net.*; public class ReverseTest { public static void main(String[] args) { try { if (args.length != 1) { System.err.println("Usage: java ReverseTest string_to_reverse");

System.exit(1); } String stringToReverse = URLEncoder.encode(args[0]); URL url = new URL("http://java.sun.com/cgi-bin/backwards"); URLConnection connection = url.openConnection(); PrintStream outStream = new PrintStream(connection.getOutputStream()); outStream.println("string=" + stringToReverse); outStream.close(); DataInputStream inStream = new DataInputStream(connection.getInputStream()); String inputLine; while ((inputLine = inStream.readLine()) != null) { System.out.println(inputLine); } inStream.close(); } catch (MalformedURLException me) { System.err.println("MalformedURLException: " + me); } catch (IOException ioe) { System.err.println("IOException: " + ioe); } } }

Let's examine the program and see how it works. First, the program processes its command line arguments: if (args.length != 1) { System.err.println("Usage: java ReverseTest string_to_reverse"); System.exit(1); } String stringToReverse = URLEncoder.encode(args[0]); These lines ensure that the user provides one and only one command line argument to the program and encodes it. The command line argument is the string to be reversed by the cgi-bin script backwards. The command line argument may have spaces or other non-alphanumeric characters in it. Those characters must be encoded because various processing may happen on the string on its way to the server. This is achieved by the URLEncoder class. Next the program creates the URL object--the URL for the backwards script on java.sun.com.

URL url = new URL("http://java.sun.com/cgi-bin/backwards"); Next, the program creates a URLConnection and then opens an output stream on that connection. The output stream is filtered through a PrintStream. URLConnection connection = url.openConnection(); PrintStream outStream = new PrintStream(connection.getOutputStream()); The second line above calls the getOutputStream() method on the connection. If the URL does not support output, this method throws an UnknownServiceException. If the URL supports output, then this method returns an output stream that is connected to the standard input stream of the URL on the server side--the client's output is the server's input. Next, the program writes the required information to the output stream and closes the stream: outStream.println("string=" + stringToReverse); outStream.close(); This line writes to the output stream using the println() method. So you can see, writing data to a URL is as easy as writing data to a stream. The data written to the output stream on the clientside is the input for the backwards script on the server-side. The ReverseTest program constructs the input in the form required by the script by concatenating string= to the encoded string to be reversed. Often, as with this example, when you are writing to a URL you are passing information to a cgibin script which reads the information you write, performs some action and then sends information back to you via the same URL. So it's likely that you will want to read from the URL after you've written to it. The ReverseTest program does that next: DataInputStream inStream = new DataInputStream(connection.getInputStream()); String inputLine; while (null != (inputLine = inStream.readLine())) { System.out.println(inputLine); } inStream.close();

Lecture-8 Topic: Advanced Socket programming (i)Advanced java client (ii)advanced java server (iii)Multithreaded java server

Advanced java client:


import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; class SocketClient extends JFrame implements ActionListener { JLabel text, clicked; JButton button; JPanel panel; JTextField textField; Socket socket = null; PrintWriter out = null; BufferedReader in = null; SocketClient(){ //Begin Constructor text = new JLabel("Text to send over socket:"); textField = new JTextField(20); button = new JButton("Click Me"); button.addActionListener(this); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add("North", text); panel.add("Center", textField);

panel.add("South", button); } //End Constructor public void actionPerformed(ActionEvent event){ Object source = event.getSource(); if(source == button){ //Send data over socket String text = textField.getText(); out.println(text); textField.setText(new String("")); //Receive text from server try{ String line = in.readLine(); System.out.println("Text received :" + line); } catch (IOException e){ System.out.println("Read failed"); System.exit(1); { { { public void listenSocket(){ //Create socket connection try{ socket = new Socket("kq6py", 4444); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); } catch (UnknownHostException e) { System.out.println("Unknown host: kq6py.eng"); System.exit(1); } catch (IOException e) { System.out.println("No I/O"); System.exit(1); { { public static void main(String[] args){ SocketClient frame = new SocketClient(); frame.setTitle("Client Program"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); { ;{ frame.addWindowListener(l); frame.pack(); frame.setVisible(true); frame.listenSocket();

} }

Advanced java server:

import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; class SocketServer extends JFrame implements ActionListener { JButton button; JLabel label = new JLabel("Text received over socket:"); JPanel panel; JTextArea textArea = new JTextArea(); ServerSocket server = null; Socket client = null; BufferedReader in = null; PrintWriter out = null; String line; SocketServer(){ //Begin Constructor button = new JButton("Click Me"); button.addActionListener(this); panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add("North", label); panel.add("Center", textArea); panel.add("South", button); } //End Constructor public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if(source == button){ textArea.setText(line); { { public void listenSocket(){ try{ server = new ServerSocket(4444);

} catch (IOException e) { System.out.println("Could not listen on port 4444"); System.exit(-1); { try{ client = server.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); system.exit(-1); { try{ in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); { while(true){ try{ line = in.readLine(); //Send data back to client out.println(line); } catch (IOException e) { System.out.println("Read failed"); System.exit(-1); { { { protected void finalize(){ //Clean up try{ in. Close(); out.close(); server.close(); } catch (IOException e) { System.out.println("Could not close."); System.exit(-1); { { public static void main(String[] args){ SocketServer frame = new SocketServer(); frame.setTitle("Server Program"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) {

System.exit(0); { ;{ frame.addWindowListener(l); frame.pack(); frame.setVisible(true) frame.listenSocket(); } }

Multithreaded Java Server: import java.awt.Color; import java.awt.BorderLayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; class ClientWorker implements Runnable { private Socket client; private JTextArea textArea; ClientWorker(Socket client, JTextArea textArea) { this.client = client; this.textArea = textArea; { public void run(){ String line; BufferedReader in = null; PrintWriter out = null; try{ in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); } catch (IOException e) { System.out.println("in or out failed"); System.exit(-1); { while(true){ try{ line = in.readLine(); //Send data back to client out.println(line); textArea.append(line);

} catch (IOException e) { System.out.println("Read failed"); System.exit(-1); { { { { class SocketThrdServer extends JFrame{ JLabel label = new JLabel("Text received over socket:"); JPanel panel; JTextArea textArea = new JTextArea(); ServerSocket server = null; SocketThrdServer(){ //Begin Constructor panel = new JPanel(); panel.setLayout(new BorderLayout()); panel.setBackground(Color.white); getContentPane().add(panel); panel.add("North", label); panel.add("Center", textArea); } //End Constructor public void listenSocket(){ try{ server = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port 4444"); System.exit(-1); { while(true){ ClientWorker w; try{ w = new ClientWorker(server.accept(), textArea); Thread t = new Thread(w); t.start(); } catch (IOException e) { System.out.println("Accept failed: 4444") System.out.println("Accept failed: 4444"); System.exit(-1); { { { protected void finalize(){ //Objects created in run method are finalized when //program terminates and thread exits try{ server.close(); } catch (IOException e) {

System.out.println("Could not close socket"); System.exit(-1); { { public static void main(String[] args){ SocketThrdServer frame = new SocketThrdServer(); frame.setTitle("Server Program"); WindowListener l = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } ;{ frame.addWindowListener(l); frame.pack(); frame.setVisible(true); frame.listenSocket(); } }

Vous aimerez peut-être aussi