Java Network Programming summary under __ algorithm

Source: Internet
Author: User
Tags url example


Java Network Programming Basics

TCP/UDP Protocol

the TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) protocols belong to the Transport layer protocol.

 

IP Protocol

IP Protocol (Internet Protocol), also known as Internet Protocol, is a datagram protocol that supports interconnection between networks, and it forms the core of TCP/IP protocol family together with TCP protocol (transmission protocol).

IP Address

TCP/IP addresses the source address and destination address

IP address function: In order to achieve communication between different computers in the network, each machine must have a distinctive identification---IP address;

IP address format: Digital, 32-bit, consists of 4 8-bit binary numbers, each 8-bit separated by dots, such as: 166.111.78.98;

IP Address composition: Network Identification (NETID) + host identification (HOSTID);

Java Networking features

The network functionality provided by Java can be broadly divided into three broad categories:

URLs and URLConnection

Socket

Datagram

URL class and URLConnection class

URL (Uniform Resource Locator)----A Uniform Resource locator that represents the address of a resource on the Internet.

 

URL composition : protocol name and resource name

Protocol:resourcename

 

URL Example :

–http://www.sun.com/

–http://home.netscape.com/home/welcome.html

–http://http://www.sun.com.cn/developers/

Create a URL class object

Common construction methods

–public URL (String spec);

URLU1 = new URL ("http://www.cctv.com.cn/default.shtml"); Public URL (Urlcontext, String spec);

URLU2 = new URL (u1, "sports.html");

–public URL (String protocol,string Host, string file);

URL U3 = new URL ("http", "www.sun.com", "developers/index.html");

–public URL (string protocol,string host, int port, string file);

URLu4 = new URL ("http", "www.sun.com", "developers/index.html");

methods for obtaining object features in the URL class

Some of the most basic methods in the URL class are as follows:

Publicfinal obect getcontent (); This method obtains the transport protocol.

Publicstring GetFile (); This method obtains the file name of the resource.

public Stringgethost (); This method gets the name of the machine.

Publicint Getport (); This method gets the port number.

public Stringgetprotocol (); This method obtains the transport protocol.

public stringtostring (); This method converts the URL into a string

creation and use of URL objects

Import java.net.*;

Import java.io.*;

Class Testurl

{public static void main (String args[]) {

try{

URL Url=newurl ("http://www.cctv.com.cn/default.shtml");

System.out.println ("The Protocol:" +url.getprotocol ());

System.out.println ("The Hostname:" +url.gethost ());

SYSTEM.OUT.PRINTLN ("The Port:" +url.getport ());

System.out.println ("Thefile:" +url.getfile ());

System.out.println (Url.tostring ());

}

catch (Malformedurlexception e) {

System.out.println (e);

}

}

}

get the contents of a URL object

importjava.io.*;

importjava.net.*;

Public class urlreader{

publicstatic void Main (String args[]) {

try{URL Tirc = Newurl ("http://www.tsinghua.edu.cn/");

Bufferedreaderin = new BufferedReader (New

InputStreamReader (Tirc.openstream ()));

Strings;

While ((s= in.readline ())!=null)

System.out.println (s);

In.close ();

}catch (malformedurlexceptione) {

System.out.println (e);

}catch (ioexceptione) {

System.out.println (e);

              }     

   }

}

 

URLConnection class

The general method for using the URLConnection object is as follows:

(1) Create a URL object.

(2) The OpenConnection () method that invokes the URL object creates the URLConnection object for the URL.

(3) Configure URLConnection.

(4) Read the header field.

(5) Get the input stream and read the data.

(6) Get the output stream and write the data.

(7) Close the connection.

the creation and use of URLConnection objects

importjava.io.*;

importjava.net.*;

import java.util.Date;

class Testurlconnection

{public static void main (String args[]) throws Exception

{System.out.println ("starting ...");

INTC;

urlurl=new URL ("http://www.baidu.com");

urlconnection urlcon=url.openconnection ();

System.out.println ("Thedate is:" +new Date (Urlcon.getdate ());

System.out.println ("Content_Type:" +urlcon.getcontenttype ());

Inputstreamin=urlcon.getinputstream ();

While ((C=in.read ())!=-1 )

{System.out.print ((char) c);}

in.close ();

       }

}

InetAddress class

Creating InetAddress Objects

Public staticinetaddress Getlocalhost ()

Public staticinetaddress Getbyname (String host)

Public staticinetaddress[] Getallbyname (String host)

the use of Inteaddress class methods

importjava.net.*;

importjava.io.*;

Public class testaddress{

publicstatic void Main (String args[]) {

try{

Inetaddressinetadd;

inetadd=inetaddress.getlocalhost ();

System.out. println ("Hostname=" +inetadd.gethostname ());

System.out. println ("Hostname=" +inetadd.gethostaddress ());

System.out. println (Inetadd.tostring ());}

catch (exceptione) {

System.out.println (e);

              }

application of socket socket

Two Java applications can exchange data through a two-way network communication connection, one end of the two-way link is called a socket.

Sockets are commonly used to implement client-server connections.

The two class sockets and ServerSocket defined in the java.net package are used to implement a two-way connection between the client and the server side

Required addressing information when establishing a connection

– The machine name or IP address of the remote computer

– The port number that you are trying to connect to (port numbers)

four basic steps for socket programming

Create a socket; Open the input/output stream connected to the socket, read/write the socket according to a certain protocol, and close the socket;

Create a socket

the construction method of Socket/serversocket class

Socket (inetaddress address,int port);

Socket (inetaddress address, int port, Boolean stream);

Socket (String host, int port);

Socket (String host, int port, Boolean stream);

serversocket (int port);

serversocket (int port, int count);

Socket Application Example-server side

importjava.net.*;

importjava.io.*;

Public class TestServer {

Public static void Main (String args[]) {

try {serversocket s = new ServerSocket (9876);

While (true) {

Socket S1 = s.accept ();

outputstream OS = S1.getoutputstream ();

DataOutputStream dos = newdataoutputstream (OS);

Dos.writeutf "Hello,socket is veryintersting!" + "\ n bye-bye!");

dos.close ();

s1.close ();}

}catch (IOException e) {System.out.println ("error:" + e);}

         }

}

Socket Application Example--client

importjava.net.*;

importjava.io.*;

Public class TestClient {

Public static void Main (String args[]) {

try{

Sockets1 = new Socket ("127.0.0.1", 9876);

Inputstreamis = S1.getinputstream ();

Datainputstreamdis = new DataInputStream (is);

System.out.println (Dis.readutf ());

dis.close ();

s1.close ();

}catch (connectexception connexc) {

System.err.println ("Server connection failed.") ");

}catch (IOException e) {}

         }

}

application of datagram sockets

Import java.net.*;

public class Udpscan

{public static void main (String args[])

{for (intport=1024;port<=65535;port++) {

try {datagramsocketserver=new datagramsocket (port);

Server.close (); }

catch (SocketException e) {

System.out.println ("There is a server in port" +port+ ");}

}

}

}

Datagram Socket Application

importjava.net.*;

Import java.io.*;

public class TestClient {

public static void Main (String args[]) {

try{

Sockets1 = new Socket ("127.0.0.1", 8888);

Inputstreamis = S1.getinputstream ();

Datainputstreamdis = new DataInputStream (IS);

System.out.println (Dis.readutf ());

Dis.close ();

S1.close ();

}catch (Connectexception connexc) {

SYSTEM.ERR.PRINTLN ("Server connection failed.") ");

}catch (IOException e) {

}

}

}

About network programming, it's basically these things, for the basic part of the network, in the actual programming will not be used, more commonly used is UDP and TCP protocol programming and socket programming parts, this is very heavy, there are several commonly used in the network programming part of several common classes, but also we should master.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.