Java Network Programming

Source: Internet
Author: User
Tags get ip

InetAddress class

The 1.InetAddress is used to represent an IP address. An Inetadress object represents an IP address.

2. How to create an InetAddress object: Getbyname (String host)

3.getHostName (): Gets the domain name corresponding to the IP address

Gethostaddress (): Get IP Address

Socket-based TCP programming

The client socket work process consists of the following basic steps

1. Create a Socket object that indicates the IP address of the server and the port number of the receiving program through the constructor

2.getOutputStream (): Send data, method returns OutputStream object

3. The specific output process

4. Close the corresponding stream and socket object

The process of working with a server program consists of the following basic steps:

1. Create an ServerSocket object that indicates its own port number through the constructor

2. Call its accept () method to return the object of a socket

3. Call the getInputStream () of the socket object to get an input stream sent from the client

4. Operations on the acquired input stream

5. Close the corresponding stream and the socket, ServerSocket object

TCP Programming Example three: Send a file from the client to the server, the server is saved to the local. and returns "sent successfully" to the client. and close the appropriate connection. To use try-catch-finally!! when handling exceptions, as in the program below This example is only convenient for writing ~public class TestTCP3 {@Testpublic void Client () throws EXCEPTION{//1. Create socket object Socket SOCKET = new Socket ( Inetaddress.getbyname ("127.0.0.1"), 9898);//2. Get a file from the local send to the server outputstream OS = Socket.getoutputstream (); FileInputStream fis = new FileInputStream (New File ("1.jpg")); byte[] B = new Byte[1024];int len;while (len = Fis.read (b))! =-1) {os.write (B,0,len);} Socket.shutdownoutput ();//3. Receive information from the server InputStream is = Socket.getinputstream (); byte[] B1 = new Byte[1024];int len1; while ((Len1 = Is.read (B1))! =-1) {String str = new string (B1,0,LEN1); System.out.print (str);} 4. Close the corresponding stream and socket object Is.close (); Os.close (); Fis.close (); Socket.close ();} @Testpublic void Server () throws EXCEPTION{//1. Create a ServerSocket object ServerSocket ss = new ServerSocket (9898);//2. Call its accept () method to return a socket object socket s = ss.accept ();//3. Saves the information sent from the client to local inputstream is = S.getinputstream (); FileOutputStream fos = new FileOutputStream (new File ("3.jpg")); byte[] B = new Byte[1024];int len;while (len = Is.read (b))! =-1) {fos.write (b, 0, Len);} System.out.println ("received from" + s.getinetaddress (). Gethostaddress () + "file");//4. Send "receive success" Feedback to client outputstream OS = S.getoutputstream (); Os.write ("You send the picture I have received successfully!") ". GetBytes ());//5. Close the corresponding stream and socket and ServerSocket object Os.close (); Fos.close (); Is.close (); S.close (); Ss.close ();}}
UDP network communication

Class Datagramsocket and Datagrampacket implement a network program based on UDP protocol.

The UDP datagram sends and receives through the datagram socket datagramsocket, the system does not guarantee that the UDP datagram can be sent to the destination safely, nor is it certain when it can arrive.

The Datagrampacket object encapsulates a UDP datagram that contains the IP address and port number of the sending side and the IP address and port number of the receiving end.

Each datagram in the UDP protocol gives the full address information, so there is no need to establish a connection between the sender and the receiver

Process

public class Testudp {//send end @testpublic void Send () {datagramsocket ds = null;try {ds = new Datagramsocket (); byte[] B = "You OK, I'm going to send the data ". GetBytes ();//Create a datagram: Each datagram cannot be greater than 64k, it records data information, the IP of the sender, the port number, and the IP, port number of the receiving end to send to//. Datagrampacket pack = new Datagrampacket (b, 0, B.length,inetaddress.getbyname ("127.0.0.1"), 9090);d s.send (pack);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{if (ds! = null) {Ds.close ();}}} Receive End @testpublic void Rceive () {datagramsocket ds = null;try {ds = new Datagramsocket (9090); byte[] B = new byte[1024];D at Agrampacket pack = new Datagrampacket (b, 0, b.length);d s.receive (Pack); String str = new String (Pack.getdata (), 0, Pack.getlength ()); System.out.println (str);} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{if (ds! = null) {Ds.close ();}}}}
URL programming

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

The basic structure of the URL consists of 5 parts:

< transport protocol >://< host name >:< port number >/< file name > Example: http://192.168.1.100:8080/helloworld/index.jsp

Constructors

  Public URL (string spec): A URL object can be constructed from a string that represents a URL address. For example: url url = new URL ("http://www. atguigu.com/");

  Public URL (url context, String spec): Constructs a URL object from a base URL and a relative URL. For example: url downloadurl = new URL (url, "download.html")

  Public URL (string protocol, string host, string file); For example: The new URL ("http", "www.atguigu.com", "Download"). HTML ");

  Public URL (string protocol, string host, int port, string file); For example: url gamelan = new URL ("http", "www.atguigu.com", "download.html");

After a URL object is generated, its properties cannot be changed, but the properties can be obtained by the method it is given:

public string Getprotocol (  )     gets the protocol name of the URL public string gethost (  )           gets the host name of the URL public string Getport (  )            Gets the port number of the URL public string GetPath (  )           Gets the file path of the URL public string getFile (  ) gets the             filename of the URL public string GetRef (  )             gets the relative position of the URL in the file public String getquery (   )        gets the query name for the URL

Url method OpenStream (): Can read data from the network

If both the input of the data and the output of the data, consider using the URLConnection

URLConnection: Represents the connection to the remote object referenced by the URL. When a connection is established with a URL, the corresponding URLConnection object is generated first on a URL object through Method OpenConnection (). If the connection process fails, a ioexception is generated.

URL netchinaren = new URL ("http://www.atguigu.com/index.shtml"); Urlconnectonn u = netchinaren.openconnection ();

The input and output streams obtained through the URLConnection object can interact with existing CGI programs.

Public Object getcontent () throws Ioexceptionpublic int getcontentlength () public String getcontenttype () public long get Date () Public long getlastmodified () public InputStream getInputStream () throws Ioexceptionpublic Outputsteram Getoutputstream () throws IOException

Java Network Programming

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.