Java Network Programming (II)

Source: Internet
Author: User

The following example starts the content of this article:

Example 1, requirements: uploading images.

Client:

    1. The service endpoint.
    2. Read the image data that the client already has.
    3. The data is sent to the server via the socket output stream.
    4. Reads the service-side feedback information.
    5. Shut down.
classpicclient { Public Static voidMain (string[] args)throwsIOException {/** A series of judgments*/        if(Args.length! = 1) {System.out.println ("Please select a picture in JPG format"); return; } File File=NewFile (args[0]); if(! (File.exists () &&file.isfile ())) {System.out.println ("The file is problematic, either does not exist, or it is not a file"); return; }        if(!file.getname (). EndsWith (". jpg") {System.out.println ("Picture format is wrong, please re-select"); return; }        if(File.length () > 1024*1024*10) {System.out.println ("The file is too large.); return; } Socket S=NewSocket ("10.48.62.209", 10007); FileInputStream FIS=Newfileinputstream (file); OutputStream out=S.getoutputstream (); byte[] buf =New byte[1024]; intLen = 0;  while(len = Fis.read (BUF))! =-1) {out.write (buf,0, Len); }                //Tell the server that the data has been finished s.shutdownoutput (); InputStream in=S.getinputstream (); byte[] Bufin =New byte[1024]; intnum =In.read (Bufin); System.out.println (NewString (Bufin, 0, num));        Fis.close ();    S.close (); }}

Service side:

This server has a limitation, when a client is connected, the server gets to it, and the server executes the specific process. At this point the B client connects, only wait, because the server has not finished processing the a client's request, has not cycled back to execute the next Accpet () method, so temporarily get the B client object.

In order to allow multiple clients to concurrently access the server side, it is best to encapsulate each client in a separate thread so that multiple client requests can be processed at the same time.

So how do you define threads?

Just define the code that each client executes on the server. Save the code in the Run () method.

classPicthreadImplementsRunnable {PrivateSocket S; Picthread (Socket s) { This. S =s; } @Override Public voidrun () {intCount = 1; String IP=s.getinetaddress (). gethostaddress (); Try{System.out.println (IP+ "... connected."); InputStream in=S.getinputstream (); File File=NewFile (ip+ "(" + (count) + ")" + ". jpg");//10.48.62.209 (1). jpg             while(File.exists ()) {file=NewFile (ip+ "(" + (count++) + ")" + ". jpg"); } FileOutputStream Fos=Newfileoutputstream (file); byte[] buf =New byte[1024]; intLen = 0;  while(len = In.read (BUF))! =-1) {fos.write (buf,0, Len); } OutputStream out=S.getoutputstream (); Out.write ("Upload succeeded". GetBytes ());            Fos.close ();        S.close (); } Catch(IOException e) {Throw NewRuntimeException (ip+ "Upload failed"); }    }    }
classPicserver { Public Static voidMain (string[] args)throwsIOException {serversocket ss=NewServerSocket (10007);  while(true) {Socket s=ss.accept (); NewThread (NewPicthread (s)). Start (); }        //ss.close ();    }    }

I think multithreading is more difficult to understand, so the above principle is illustrated:

Example 2, the client input user name through the keyboard. This user name is verified by the server. If the user exists, the server displays XXX and is logged in. 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 3 times.

The following is the code, the Guide package is not guided.

Client:

classloginclient { Public Static voidMain (string[] args)throwsIOException {Socket s=NewSocket ("10.48.62.209", 10008); BufferedReader BUFR=NewBufferedReader (NewInputStreamReader (system.in)); PrintWriter out=NewPrintWriter (S.getoutputstream (),true); BufferedReader Bufin=NewBufferedReader (NewInputStreamReader (S.getinputstream ()));  for(intx = 0; x < 3; X + +) {            /** CTRL + C key on the keyboard, that is, the end input * Read () method returns the -1,readline () method returns null*/String Line= Bufr.readline ();//Ctrl + C, then -1,readline () returns null            if(line = =NULL)                  Break;            Out.println (line); String Info=Bufin.readline (); System.out.println ("INFO:" +info); if(Info.contains ("Welcome"))                 Break;        } bufr.close (); S.close ();//A 1 is added to the socket stream, which is equivalent to adding an end tag to the stream, which is -1    }}

Service side:

classUserthreadImplementsRunnable {PrivateSocket S; Userthread (Socket s) { This. S =s; } @Override Public voidrun () {String IP=s.getinetaddress (). gethostaddress (); SYSTEM.OUT.PRINTLN (IP+ "...... connected."); Try {             for(intx = 0; x < 3; X + +) {BufferedReader Bufin=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); /** Read () returns -1,readline () returns NULL when typing CTRL + C key on the client side. * So name has to add a judgment*/String name=Bufin.readline (); if(Name = =NULL)                      Break; /** Check*/BufferedReader BUFR=NewBufferedReader (NewFileReader ("User.txt")); PrintWriter out=NewPrintWriter (S.getoutputstream (),true); String Line=NULL; Boolean flag = false;//definition tag                 while(line = Bufr.readline ())! =NULL) {                    if(line.equals (name)) {flag=true;  Break; }                }                if(flag) {SYSTEM.OUT.PRINTLN (name+ ", Logged in"); OUT.PRINTLN (Name+ "Welcome to");  Break; } Else{System.out.println (name+ "Try to sign in"); OUT.PRINTLN (Name+ ", user name does not exist");        }} s.close (); } Catch(IOException e) {Throw NewRuntimeException (ip+ "checksum failed"); }    }    }
class Loginserver {    publicstaticvoidthrows  IOException {         New ServerSocket (10008);          while (true) {            = ss.accept ();             New Thread (new  Userthread (s)). Start ();     }}

Demo client and server side

1.

Client: Browser, telnet (telnet command--connect to any host on the network under DOS command line)

Cases:

Telnet 10.48.62.209 11000

  

Java Network Programming (II)

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.