Black Horse Programmer--java Foundation--Network programming

Source: Internet
Author: User



Black Horse Programmer--java Foundation--Network programming

------Java Training, Android training, iOS training,. NET training, look forward to communicating with you! -------

Several basic concepts

Network communication three elements: IP address, port number, transmission protocol

IP Address:

It is a device identifier in the network, and Java corresponds to the InetAddress class, which is present in the java.net package.

Port number:

A, the logical address used to identify the process, without the identity of the process.

b, valid port: 0 ~65535, the system is used or reserved port is: 0~ 1024.

Transport protocol:

That is, communication rules, including TCP and UDP protocols

Socket

Socket, the endpoint of the communication .

is to provide a mechanism for network services, both ends of the communication socket, network communication is actually the communication between sockets , data in two sockets through IO transmission.

Example:


public class Netdemo {public static void main (string[] args) throws Exception {//TODO auto-generated method Stubsocket s = new Socket ("www.baidu.com", 8080); BufferedReader br = new BufferedReader (New InputStreamReader (S.getinputstream ())); String Line;while (line = Br.readline ())! = null) {System.out.println (line);}}}

TCP Transport

After the establishment of the two endpoints, there is a channel to transmit the data, which is called the stream, and is a stream based on the network, called the socket stream. There are both reads and writes in the stream.

Two endpoints for TCP:

One is the client and one is the server.

Client: Corresponding object,Socket

Server: Corresponding object,ServerSocket

TCP Client:

1, to establish a TCP socket Service, it is best to specify the specific address and port. When this object is created, it is already possible to connect to the specified IP and Port ( three handshake ).

2, if the connection is successful, it means that the channel is established, thesocket flow has been generated. As long as you get the read stream and write stream to the socket stream, you can get two stream objects through getinputstream and getoutputstream .

3, close the resource.

TCP Service side:

1, create the service-side socket service and listen to a port.

2, the server in order to provide services to the client, get the contents of the client, you can get the client object connected through the accept method.

3, you can communicate by getting the socket stream in the socket object and the specific client.

4, if the communication is over, close the resource. Note: To close the client first, then close the server.

TCP Client

public class TcpClient {public static void main (string[] args) throws Exception {//TODO auto-generated method Stubsocket S;s = new Socket ("127.0.0.1"), OutputStream OS = S.getoutputstream (); Os.write ("Hello". GetBytes ()); InputStream is = S.getinputstream (); byte[] buff = new Byte[1024];int Len;len = Is.read (buff); System.out.println (New String (buff, 0, Len)); S.close ();}}

TCP Service Side

public class TCPServer {public static void main (string[] args) throws Exception {ServerSocket ss = new ServerSocket (1000); Socket s = ss.accept (); String IP = s.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP + "is connected"), InputStream is = S.getinputstream (); byte[] buff = new Byte[1024];int len = Is.read (buff); System.out.println (New String (buff, 0, Len)), OutputStream OS = S.getoutputstream (); Os.write ("Received". GetBytes ()); S.close (); Ss.close ();}}

Impersonate a client Login

The client enters the user name via the keyboard.
This user name is verified by the server.

If the user exists, on the server display XXX, has landed.
And on the client display XXX, welcome to visit.

If the user does not exist, show xxx on the server and try to log in.
And the client displays XXX, the user does not exist.

Log in at most three times.

public class Loginclient {public static void main (string[] args) throws Exception {//TODO auto-generated method stub//Definition Socketsocket s = new Socket ("192.168.1.102", 10008); BufferedReader br = new BufferedReader (new InputStreamReader (system.in)); PrintWriter pw = new PrintWriter (S.getoutputstream ()); BufferedReader Br2 = new BufferedReader (New InputStreamReader (S.getinputstream ())); for (int i = 0; i < 3; i++) {String line = Br.readline (), if (line = = null) {break;} Pw.print (line); String line2 = Br2.readline (); System.out.println (line2); if (Line2.contains ("Welcome")} {break;}} Br.close ();p w.close (); Br2.close (); S.close ();}}  public class Loginserver {public static void main (string[] args) {//TODO auto-generated method Stubtry {ServerSocket SS = New ServerSocket (10008); while (true) {System.out.println ("Waiting ... "); Socket s = ss.accept (); SYSTEM.OUT.PRINTLN ("receive"); New Thread (New Userthread (s)). Start ();}} catch (Exception e) {e.printstacktrace ();}}} Class Userthread implements Runnable {Socket s; UserthreaD (Socket s) {THIS.S = s;} @Overridepublic void Run () {String IP = s.getinetaddress (). gethostaddress (); try {System.out.println ("IP:" + IP + "is conn "); for (int i = 0; I < 3; i++) {BufferedReader br = new BufferedReader (New InputStreamReader (S.getinputstream ())); String name;if ((name = Br.readline ()) = = null) {break;} BufferedReader Br2 = new BufferedReader (New FileReader ("User.txt")); String Line;boolean flag = false;while ((line = Br2.readline ()) = null) {if (line.equals (name)) {flag = True;break;}} PrintWriter pw = new PrintWriter (S.getoutputstream ()), if (flag) {PW.PRINTLN (name + ", welcome"); break;} else {pw.println ( Name + ", user name does not exist");}} S.close ();} catch (Exception e) {throw new RuntimeException (IP + "checksum failed");}}}
Browser presentation for clients and services

Browser is a standard client, it can be sent over the service side of the data message to resolve, the application-level protocol to meet the message part of the resolution, the header information is removed, transferred to the application layer, only the correct body of the subject part of the topic is displayed in the main section.

And because Java compilation is handled at the transport and internetwork levels, all messages are accepted, including the header message. While the browser is in the application layer, the header message sent is removed, leaving only the subject information.

/* * in Browser input: Http://localhost:11000/* can be accessed, return to "Client Hello" */public class Serverdemo {public static void main (string[] args) thr oWS Exception {ServerSocket ss = new ServerSocket (11000); System.out.println ("Waiting to receive ..."); Socket s = ss.accept (); SYSTEM.OUT.PRINTLN ("Success"); System.out.println (S.getinetaddress (). gethostaddress ()); InputStream in = S.getinputstream (); byte[] buf = new byte[ 1024];int len = In.read (BUF); System.out.println (New String (buf, 0, Len));//return information written to client output stream PrintWriter out = new PrintWriter (S.getoutputstream (), True) ;//True be sure to write Out.println ("<font color= ' Red ' size= ' 7 ' > Client Hello </font>"); S.close (); Ss.close ();}}
URLs and URLConnection

1. URL:

URI: Larger range, barcode is also included in this range

URL: Small scope, that is, domain name

Method:

1) Constructor: URL (String protocol,string host,int port,string file),//Create URL object based on specified protocol, host, port number, and file.

2) String getprotocol ();//Get Protocol name

3) String gethost ();//Get host Name

4) int getport ();//Get Port number

5) String getFile ();//Get URL file name

6) String GetPath ();//Gets the path portion of this URL

7) String getquery ();//Gets the query portion of this URL, the specific information that the client transmits

Note: The general input URL, is not with the port number, at this time can be obtained, by obtaining the URL returned by port, if Port is-1, then assign a default 80 port, such as

int port = Getport ();

if (port = =-1)

Port = 80;

2, URLConnection

Method:

1) urlconnection openconnection (); Call this method with a URL to return a URLConnection object that represents the connection to the remote object referenced by the URL.

2) InputStream getinputstream ();//Get input stream

3) OutputStream Getoutputstream ();//Get output stream
Example

public class Urlconnectiondemo {public static void main (string[] args) {//TODO auto-generated method stub/*try {URL url = New URL ("http://www.baidu.com"); URLConnection conn = Url.openconnection (); InputStream is =conn.getinputstream (); byte[] buff = new Byte[1024];int Len;len = Is.read (buff); System.out.println (New String (buff, 0, Len));} catch (Malformedurlexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} */url url;try {url = new URL ("http://192.168.1.254/myweb/demo.html?name=haha&age=30"); System.out.println ("Getprotocol ():" +url.getprotocol ()); System.out.println ("GetHost ():" +url.gethost ()); System.out.println ("Getport ():" +url.getport ()); System.out.println ("GetPath ():" +url.getpath ()); System.out.println ("GetFile ():" +url.getfile ()); System.out.println ("Getquery ():" +url.getquery ());/*int port = Getport (); if (port==-1) port = 80;getport () ==-1*/} catch (Malformedurlexception e) {//TODO Auto-generated catch Blocke.printstacktrace ();}}} /* * GETPROTOCOL (): Httpgethost (): 192.168.1.254getPort (): -1getpath ():/myweb/demo.htmlgetfile ():/myweb/demo.html? Name=haha&age=30getquery (): name=haha&age=30 */















Black Horse Programmer--java Foundation--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.