Java Basic Knowledge Network programming (TCP practice)

Source: Internet
Author: User

Exercise: Copying text

Practice requirements: To send a client's file content to the server, on the server side of the data stored in a file. equivalent to copying files.

Importjava.io.*;ImportJava.net.*;class txtcopytestclient{ Public Static void Main(string[] args)throwsException {Socket s=NewSocket ("192.168.1.6",10003); BufferedReader bur=NewBufferedReader (NewInputStreamReader (NewFileInputStream ("Client.txt")));//bufferedwriter buwout=new BufferedWriter (New OutputStreamWriter (S.getoutputstream ()));PrintWriter pw=NewPrintWriter (S.getoutputstream (),true); String line=NULL; while((Line=bur.readline ())! =NULL) {pw.println (line);        } s.shutdownoutput (); BufferedReader burin=NewBufferedReader (NewInputStreamReader (S.getinputstream ()));        String Str=burin.readline ();        System.out.println (str);        Bur.close ();    S.close (); }}class txtcopytestserver{ Public Static void Main(string[] args)throwsException {ServerSocket ss=NewServerSocket (10003);        Socket s=ss.accept (); BufferedReader burin=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); PrintWriter pw=NewPrintWriter (NewFileOutputStream ("Server.txt"),true); String line=NULL; while((Line=burin.readline ())! =NULL) {pw.println (line);        } pw.close (); PrintWriter pwout=NewPrintWriter (S.getoutputstream (),true); Pwout.println ("Upload succeeded");        S.close ();    Ss.close (); }}
Exercise 2: Uploading pictures
Import Java.io.*;import java.net.*;class picclient { Public Static void Main(string[] args) throws Exception {Socket s=NewSocket ("192.168.1.114",10003); FileInputStream fis=NewFileInputStream ("Pictest.jpg"); OutputStream Os=s.getoutputstream ();byte[] buf=New byte[1024x768];intlen=0; while((Len=fis.read (BUF))!=-1) {Os.write (buf,0, Len);        } s.shutdownoutput (); InputStream is=s.getinputstream ();byte[] re=New byte[1024x768];intLength= is. read (re); String str=NewString (Re,0, length); System. out. println (str);        Fis.close ();    S.close (); }}class picserver{ Public Static void Main(string[] args) throws Exception {ServerSocket ss=NewServerSocket (10003);        Socket s=ss.accept (); InputStream is=s.getinputstream (); FileOutputStream fos=NewFileOutputStream ("Serverpic.jpg");byte[] buf=New byte[1024x768];intlen=0; while((len= is. Read (BUF))!=-1) {Fos.write (buf,0, Len);        } outputstream Os=s.getoutputstream (); Os.write ("Upload succeeded". GetBytes ());        S.close ();    Ss.close (); }}
Exercise 3: Client uploads pictures concurrently
Import Java.io.*;import Java.net.*;class uploadbythreadclient{ Public Static void Main(string[] args) throws Exception {if(args.length!=1) {System. out. println ("Please select a JPG image");return; } File file=NewFile (args[0]);if(!        (File.exists () &&file.isfile ())) {System. out. println ("There is a problem with the file, either a complement exists, 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 () >1024x768*1024x768*5) {System. out. println ("The file is too large.);return; } Socket s =NewSocket ("192.168.1.114",10003); FileInputStream FIS =NewFileInputStream ("Pictest.jpg"); OutputStream out= S.getoutputstream ();byte[] buf =New byte[1024x768];intLen =0; while((Len=fis.read (BUF))!=-1)        { out. Write (BUF,0, Len); }//Tell the server that the data has been finishedS.shutdownoutput (); InputStreaminch= S.getinputstream ();byte[] Bufin =New byte[1024x768];intnum =inch. read (Bufin); System. out. println (NewString (Bufin,0, num));        Fis.close ();    S.close (); }}class uploadbythreadserver{ Public Static void Main(string[] args) throws Exception {ServerSocket ss=NewServerSocket (10003); while(true) {Socket s=ss.accept ();NewThread (NewAcceptthread (s)). Start (); }}}class Acceptthread implements runnable{PrivateSocket s; Acceptthread (Socket s) { This. s=s; } Public void Run()    {Try{InputStreaminch= S.getinputstream (); String ip=s.getinetaddress (). gethostaddress ();intCount=1; File def=NewFile (ip+"("+count+")"+". jpg"); while(Def.exists ()) {def=NewFile (ip+"("+ (count++) +")"+". jpg"); } FileOutputStream fos =NewFileOutputStream (Def);byte[] buf =New byte[1024x768];intLen =0; while((len=inch. Read (BUF))!=-1) {Fos.write (buf,0, Len); } outputstream out= S.getoutputstream (); out. Write ("Upload succeeded". GetBytes ());            Fos.close ();        S.close (); }Catch(Exception e) {Throw NewRuntimeException ("Upload failed"); }    }}

Exercise 4: Client Concurrent Login
Import Java.io.*;import java.net.*; class loginclient{     Public Static voidMain (string[] args) throws Exception {Socket s=NewSocket ("192.168.1.6",100010); BufferedReader bur=NewBufferedReader (NewInputStreamReader (system.in)); PrintWriter pw=NewPrintWriter (S.getoutputstream (),true); BufferedReader burin=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); for(intI=0;i<3; i++) {String user=bur.readline ();if(user==NULL) Break;            PW.PRINTLN (user);            String Info=burin.readline (); System.out.println ("The Feedback information is:"+info);if(Info.contains ("Welcome") {System.out.println ("Successful Landing"); Break;        }} bur.close ();    S.close (); }} class loginserver{     Public Static voidMain (string[] args) throws Exception {ServerSocket ss=NewServerSocket (100010); while(true) {Socket s=ss.accept (); System.out.println ("Connection succeeded");NewThread (NewUserloginthread (s)). Start (); }    }} class userloginthread implements Runnable{    PrivateSocket s; Userloginthread (Socket s) { This. s=s; } Public voidRun () {Try{BufferedReader burin=NewBufferedReader (NewInputStreamReader (S.getinputstream ())); for(intI=0;i<3; i++) {String user=burin.readline (); System.out.println ("username sent to:"+user);if(user==NULL) {System.out.println ("is empty"+user); Break; } BufferedReader bur=NewBufferedReader (NewFileReader ("User.txt")); String line=NULL;Booleanflag=false; while((Line=bur.readline ())! =NULL) {System.out.println ("User name found:"+line);if(line.equals (user)) {flag=true; Break; }                }if(flag) {PrintWriter pw=NewPrintWriter (S.getoutputstream (),true); Pw.println (user+"Welcome you!" "); S.close (); Break; }Else{PrintWriter pw=NewPrintWriter (S.getoutputstream (),true); Pw.println ("Please enter the correct user name");            } bur.close ();        } s.close (); }Catch(Exception e) {Throw NewRuntimeException ("Login Failed"); }    }}

Java Basic Knowledge Network programming (TCP practice)

Related Article

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.