Results 1 to 4 of 4

Thread: Introducing Java Network

  1. #1
    Join Date
    Feb 2010
    Posts
    136

    Introducing Java Network

    I. Introduction
    Since the release of java API to manage the network is available in the JDKit can manage addresses, sockets, client, socket servers, URLs. In this course we will see how to use this API by sometimes linked with the management of low level network. It is considered that you know the java.io and java.net packages briefly.

    II. Addressing
    Before the actual communication part, we will learn to use the IP addresses in java. For two applications to communicate (using IP), it is necessary to known address IP the other machine. API standard allows the manipulated using class InetAddress. This allows manipulate both addresses IPv4 that addresses IPv6. This corresponds to two different standards, most IP are encountered IPv4 and notation as 127.0.0.1.

    II-A. Obtain IP address
    Class InetAddress has a static method getLocalHost () who can get the IP address and methods getHostName() and getHostAddress() which can respectively obtain the host name and address as dotted.
    Here is the code for it

    Code:
    import java.net.InetAddress;
    import java.net.UnknownHostException;
    
    Public class TestInetAddress {
    
    	Public static void hand(String [] args) throws UnknownHostException {
    		InetAddress add = InetAddress.getLocalHost();
    
    System.out.System.out.println("Name Host : " + add.getHostName());
    
    System.out.System.out.println("IP : " + add.getHostAddress());
    	}
    
    }
    By running this code, you'll get a result that depends on your machine and your network. Most of the time, you will not get your real Internet address but a local address 127.0.0.1 or address of local network 192.168.1.x for example.

    Indeed, most of the time a machine has at least three addresses:

    - Local IP address (127.0.0.1) called localhost
    - network IP address (192.168.xx frequently on network homes)
    - IP Internet

    To get all the IP addresses of the machine, it is necessary to list all network interfaces (class NetworkInterface) and list their IP addresses. We use the static method getNetworkInterfaces from Class NetworkInterface for all network interfaces.
    Here is the code for it

    Code:
    import java.net.InetAddress;
    import java.net.NetworkInterface;
    import java.net.SocketException;
    import java.net.UnknownHostException;
    import java.util.Enumeration;
    
    Public class TestInetAddress {
    
    	Public static void hand(String [] args) throws Exception {
    		//Lists whole of inter networks, typical a map network
    		Enumeration<NetworkInterface> inter = NetworkInterface.getNetworkInterfaces();
            
            while (inter.hasMoreElements()) {  
               NetworkInterface netinter = inter.nextElement(); 
               
               //each map network may have of many Address IP
               Enumeration<InetAddress> add = netinter.getInetAddresses(); 
               while (add.hasMoreElements()) {  
                   InetAddress currentAddress = add.nextElement();
                   System.out.System.out.println(currentAddress.getHostAddress());
               }
           }
    	}
    
    }

  2. #2
    Join Date
    Feb 2010
    Posts
    136

    Re: Introducing Java Network

    III. First Communications
    To communicate between machines, Computer scientists have identified two network protocols commonly used today: Protocol TCP and protocol UDP. Fairly brief, the protocol TCP has been created for you to send data reliably over the network, including:

    - ensuring that data arrives at destination, if failure of transmission, the sending computer must be made aware
    - ensuring that data arrives out of order
    - establishing a connection between machines

    The protocol UDP adds very little to the protocol IP. Compared Protocol TCP, UDP is unreliable, it is unclear whether data arrive and it is not certain than the data arrive is in good order. TCP performs a large number of round trips, which has the disadvantage to lower connection speed. Today TCP is almost used all the time, except for trade with the packet loss is not large. Java offers several classes for handling these protocols so absolutely transparent. Class Socket based on the protocol TCP and can therefore transmit data reliably. the Class DatagramSocket in turn, depends on UDP.

    III-A. Socket client side
    Most operating systems provide an abstraction to handle data networks known as socket. Point for low-level, a socket behaves the same way a file (which is usually handled through what is called a file descriptor). Once a connection is established, the socket handling is similar to managing files. In java was introduced a class Socket to manipulate with higher-level abstraction of the operating system. There are two methods: getOutputStream () and getInputStream () which will allow you to manipulate data as a file. Java is the difference between socket client side (object allows you to connect to remote computers) and socket server side (object that can wait for connection requests from outside). Class Socket corresponds to a socket client class, ServerSocket corresponds to a socket server.

    III-A-1. The Socket class
    At first, we'll see how we connect to a server remote, how to send data and how to receive, I think this is fairly simple.

    Code:
    Socket soc = new Socket("www.cnet.com", 80);
    		
    		//or
    		InetAddress add = InetAddress.getByName("www.cnet.com");
    Socket s2 = new Socket(add, 80);
    The previous code used to connect to a server named by its IP or by its host name on a particular port (the port number 80). The concept of port, which is purely virtual, has been defined at the layer TCP and UDP to afford not to mix the data sent to a person. This is done using two different ports for two treatments. It is also possible to reuse the class InetAddress.
    We will now send data using a OutputStream.

    Code:
    Socket s = new Socket("www.cnet.com", 80);
    
    String g = "GET / HTTP/1.1 \ n" +
    					"Host: www.cnet.com \ n \ n";
    
    OutputStream str = s.getOutputStream();
    str.write(g.getBytes());
    For better management one can use BufferedInputStream and BufferedOutputStream
    Classes BufferedInputStream and BufferedInputStream allow manipulate flows more efficiently standard networks. Classes buffered work for the user, in much the same way as non-buffered classes, these classes are inherited OutputStream and InputStream. It is possible to create using directly normal flows:
    Here is an example
    Code:
    strm = s.getOutputStream();
    istrm = s.getInputStream();
    
    bin BufferedInputStream = new BufferedInputStream(strm);
    BufferedInputStream bin2 = new BufferedInputStream(istrm);
    
    bin.write(g.getBytes());
    At this level you will realize that the code does not work. Indeed, as the output stream is buffered, it is not immediately sent to the server, to force the sending, it is necessary to use the method: flush Class BufferedInputStream. In all, we have:

    Code:
    ostrm = s.getOutputStream();
    istrm = s.getInputStream();
    
    bin BufferedInputStream = new BufferedInputStream(ostrm);
    BufferedInputStream bin2 = new BufferedInputStream(istrm);
    
    bin.write(g.getBytes());
    bin.flush();
    			
    			int bts = 0;
    			while((bts = bin2.read(b)) >= 0) {
    			
    				System.out.System.out.println("We has received : " + bts + " bit");
    System.out.System.out.println("Received : " + new String(b 0, bts));
    			}
    			
    			bin.close();
    bin2.close();

  3. #3
    Join Date
    Feb 2010
    Posts
    136

    Re: Introducing Java Network

    Also one can use BufferedReader and BufferedWriter
    For reading and writing text data, java provides classes BufferedWriter and BufferedReader which are constructed from of OutputStreamReader and InputStreamReader. This offers the advantages of flow and buffered additional methods for managing direct channels character. The Class BufferedReader has such a method readLine () who can read a line (i.e ending with \ n). Class BufferedWriter has a method write who can directly write a string (the format String). The previous code can become:
    Code:
    BufferedWriter wri = new BufferedWriter(new OutputStreamWriter(
    s.getOutputStream()));
    BufferedReader rd = new BufferedReader(new InputStreamReader(
    s.getInputStream()));
    
    wri.write(g);
    wri.flush();
    
    String ln;
    while((ln = rd.readLine()) != null) {
    System.out.System.out.println("Received : " + ln);
    }
    wri.close();
    rd.close();
    III-B. Socket server side
    Until now, we have seen that communication to a server. It therefore lacks a tool that would create yourself a server waiting for requests connection from outside.

    III-B-1. Class ServerSocket
    Java offers a class called ServerSocket is dedicated the pending request connection from another machine. You often encounter the term bind. This corresponds to an assignment of an address and a port a socket. Indeed, to listen for connection requests, it is necessary to assign an address and listening port.
    Code:
    ServerSocket ser = new ServerSocket(300);
    ser.close();
    This code corresponds to the creation of a ServerSocket assigned to the local address and port 300. The method accept () waits until a connection outside.
    Code:
    ServerSocket ser = new ServerSocket(300);
    Socket Client = ser.accept();
    
    customer.close();
    ser.close();
    You can run this code and you will see that the program waits. In a console window (or Unix), specify, telnet localhost 300. You will see that the program ends. Indeed, the connection has been established and you have a class Socket to communicate. Many server applications created a dedicated thread to listen connection requests and creates a new thread per client. It is possible to use a thread in all.

  4. #4
    Join Date
    Feb 2010
    Posts
    136

    Re: Introducing Java Network

    IV. Advanced Network

    IV-A. Utility and timeout management
    When creating a server, it is necessary that it be robust, this which is generally great difficulty. Suppose we stick to what we saw earlier, i.e that we try to read on a socket until the method read returns -1. It is possible that the client tries to send many data, but without closing the socket. It is then possible the server is saturated. Java API introduced methods to manage timeouts. If the time indicated is exceeded, then the method read throws an exception.
    The Classes Socket and ServerSocket have a method setSoTimeout (int) which specifies the timeout milliesecondes. If the timeout reaches its maturity, the methods throw an exception SocketTimeoutException. For example:
    Code:
    Socket soc = new Socket("www.cnet.com", 80);
    soc.setSoTimeout(1000);
    
    
    InputStream istrm = soc.getInputStream();
    		byte[] B = new byte[1000];
    		try {
    			istrm.read(b);
    		}
    		catch (SocketTimeoutException e) {
    			System.err.System.out.println("Timeout");
    		}
    		catch(IOException e) {
    			e.printStackTrace();
    		}
    		finally {
    			istrm.close();
    soc.close();
    		}
    Note that once the timeout positioned, there is no need to redefine each call readAt method or accept.

    IV-B. Communication through a proxy
    The simplest method is to modify the parameters at the launch virtual machine (it is not necessary to modify the source code of your program)
    Code:
    java -DproxySet=true -DproxyHost=proxyname -DproxyPort=portnum test
    A second method is to modify the properties of systems via the method getProperties() Class System

    Code:
    Properties pr = System.getProperties();
    String prx = "127.0.0.1";
    String prxprt = "80";
    
    pr.could("http.proxyHost", prx);
    pr.could("http.prxprt", prxprt);
    IV-C. And use UDP datagrams
    Most network applications are based on TCP (hence Class Sockets are used) to communicate. It can sometimes be necessary to use a protocol a little easier and faster in some cases: the protocol UDP.
    Communication between two machines using the UDP protocol is sending packets (therefore this does not as flows). This protocol is considered as unreliable and runs in offline. This means that:

    - there is no one single channel (socket) to communicate between a single client and single server
    - he is not sure the data arrives at destination
    - he is not sure packages arrive in good order

    In Protocol TCP there takes many round trips between client and server (based on a system of acknowledgment) to be sure that data arrives. Sometimes one wishes communicate information quickly and that the loss of information is not very important. This is typically the case of servers streaming video, voice over IP.

Similar Threads

  1. Network Guide Part 2 - Introducing the OSI Model
    By mindreader in forum Networking & Security
    Replies: 7
    Last Post: 06-02-2013, 01:57 AM
  2. Information on introducing McAfee for 2010
    By Ceesar in forum Networking & Security
    Replies: 3
    Last Post: 06-12-2009, 05:08 AM
  3. Introducing the Thecus N5500 NAS Device
    By Paxton in forum Portable Devices
    Replies: 1
    Last Post: 15-06-2009, 10:07 PM
  4. Mozilla introducing Geode
    By mauricio in forum Windows Software
    Replies: 0
    Last Post: 08-10-2008, 07:57 PM

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Page generated in 1,713,560,868.80003 seconds with 17 queries