"Java from getting started to giving up" Javase: Network Programming (Starter Edition)

Source: Internet
Author: User

To do network programming, start by figuring out what the purpose is.

Network programming says the simple point is that the computer on the network interacts with the data.

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M00/07/18/wKiom1nDU8jBR29DAADRe0E88II285.png "title=" 11. PNG "width=" "height=" 328 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:600px;height:328px; "alt=" Wkiom1ndu8jbr29daadre0e88ii285.png "/>

Now that you want to interact with your data, you need to have a sender and a recipient.

According to the network, is an attack on a subject 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0025.gif "alt=" J_0025.gif "/>

Of course, at this stage of the Internet computer generally are both accept data, but also can send data, so that these computers are "socket type", into the offensive, back can be affected!!!

Well, use the professional name: client/server .


So how do they interact with the data, specifically to the two computers? Please see:

650) this.width=650; "src=" Https://s4.51cto.com/wyfs02/M02/A5/C9/wKioL1nDVIrikiO8AACwoz0sGOs008.png "title=" 12. PNG "width=" "height=" 359 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:600PX;HEIGHT:359PX; "alt=" Wkiol1ndvirikio8aacwoz0sgos008.png "/>

From the steps to analyze:

First, the server-side program

1.1 Creates a server socket (serversocket) and binds to the specified port.

1.2 Listens for requests from the client and returns the socket object (socket) If the connection is accepted.

1.3 Get the input/output stream, that is, the data received or sent.

1.4 Close socket (socket).

Second, the client program

2.1 Create a socket to specify an item to send the request to the server.

2.2 Start receiving or sending data after the server is properly connected.

2.3 Close the socket.


Step analysis is over, the next is implemented.

The server-side code is as follows:

public class myserver {private static final int server_port =  9527; //  Specifies the listening port public myserver ()  {try {ServerSocket ss = new  ServerSocket (server_port); //  Create a server socket SYSTEM.OUT.PRINTLN ("service side started, waiting for client ..."); Socket s = ss.accept (); //  listens for requests from clients Inputstream in = s.getinputstream (); //  obtains the input stream, which is used to receive data Outputstream out = s.getoutputstream (); //  to obtain the output stream, Used to send data byte[] buf = new byte[1024]; //  data cache Int len = in.read (BUF);  //  reading data from the input stream string strfromclient = new string (Buf, 0, len); System.out.print ("Information from the client >>"); System.out.println (strfromclient); string strtoclient =  "I am also very good! Out.write (Strtoclient.getbytes ()); //  send data to the output stream//  close the input stream and output stream in.close (); Out.close ();//  Turn off communication sockets and server Sockets S.close (); Ss.close (); SYSTEM.OUT.PRINTLN ("ServiceThe service end is closed. ");}  catch  (ioexception e)  {e.printstacktrace ();}} Public static void main (String[] args)  {MyServer ms = new  MyServer ();}}

The

Client code is as follows:

public class myclient {private static final int server_port =  The 9527;  //server listens on port public myclient ()  {try {  //because the service side is also running on this machine, So create the native InetAddress object Inetaddress address = inetaddress.getbyname ("localhost"); Socket s = new socket (address, server_port);   // The request is made to the server listening port System.out.println ("The client has started. "); Inputstream in = s.getinputstream ();      //gets the input stream to receive the data OutputStream  out = s.getoutputstream ();   //gets the output stream, which is used to send the data string strtoserver =  "Hello!" "; Out.write (Strtoserver.getbytes ());    //sends data to the output stream byte[] buf = new byte[ 1024];int len = in.read (BUF);               //reading data from the input stream string strfromserver = new string (Buf, 0, len); System.out.print ("Response from the server >>"); System.oUt.println (strFromServer); In.close (); Out.close ();   //off input stream and output stream S.close ();                //closes the communication socket SYSTEM.OUT.PRINTLN ("The client is closed. ");}  catch  (Unknownhostexception nhe)  {system.out.println ("specified host not found ...");  catch  (Ioexception ioe)  {     ioe.printstacktrace ();}} Public static void main (String[] args)  {MyClient mc = new  MyClient ();}}


Run server-side first

650) this.width=650; "src=" Https://s2.51cto.com/wyfs02/M02/A5/CA/wKioL1nDWzizH3DqAAAdegLMUa8760.png "title=" 11. PNG "alt=" Wkiol1ndwzizh3dqaaadeglmua8760.png "/>


Run the client again to see that the server-side content has changed

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M01/07/19/wKiom1nDW9zQWpbWAAAjBpnMi-k530.png "title=" 12. PNG "alt=" Wkiom1ndw9zqwpbwaaajbpnmi-k530.png "/>

Then switch to the client's output window

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M00/07/19/wKiom1nDXAzAcF5hAABHB78MZ7I848.png "title=" 13. PNG "width=" height= "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:800px;height:53px; "alt=" Wkiom1ndxazacf5haabhb78mz7i848.png "/>

The client's output reads as follows:

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M00/07/19/wKiom1nDXAzwzJCUAAAfg4FCVAI164.png "style=" float : none; "title=" 14.png "alt=" Wkiom1ndxazwzjcuaaafg4fcvai164.png "/>


Interested crossing can modify the code to make it possible to interactively enter text from the console. A friend who has studied more deeply can try to send a file.

The most basic content of network programming to end here, here should be a bit praise!!! 650) this.width=650; "src=" Http://img.baidu.com/hi/jx2/j_0028.gif "alt=" J_0028.gif "/>


"Software Thinking" blog address: 51CTO , Blog Park  , interested small partners can go to see the relevant other blog posts.


This article is from the "Software Thinking" blog, please be sure to keep this source http://softi.blog.51cto.com/13093971/1967444

"Java from getting started to giving up" Javase: Network Programming (Starter Edition)

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.