Dark Horse programmer _ Java basics 24th days _ Java Network Programming continued

Source: Internet
Author: User

 

-----------------
Java Training
Android training is expected to communicate with you ----------------------------

 

Next, we will upload an image. This is no different from the previous Upload File, except that the stream object used for file operations is a byte stream! Let's try it out!

 

 

// Server side public class tcpimage {public static void main (string [] ARGs) throws exception {serversocket Server = new serversocket (10909); Socket Client = server. accept (); // obtain the input stream inputstream of the client is = client. getinputstream (); // obtain the output stream outputstream out = client. getoutputstream (); // file storage location outputstream OS = new fileoutputstream ("server.jpg"); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = is. read ( Buffer ))! =-1) {OS. write (buffer, 0, Len);} // feedback to the client bufferedwriter BW = new bufferedwriter (New outputstreamwriter (out); BW. write ("image uploaded"); BW. flush (); OS. close (); client. close (); server. close ();}}

 

// Client class client {public static void main (string [] ARGs) throws exception {// create client service object socket = new socket ("192.168.1.102", 10909 ); inputstream in = new fileinputstream ("D: \ imagetest \ pai.jpg"); // obtain the output stream object outputstream OS = socket of the client. getoutputstream (); // obtain the input stream object inputstream of the client is = socket. getinputstream (); byte [] buffin = new byte [1024]; int Len = 0; while (LEN = in. read (buffin ))! =-1) {OS. write (buffin, 0, Len);} // tell the server that I have sent the socket. shutdownoutput (); bufferedreader BR = new bufferedreader (New inputstreamreader (is); string message = BR. readline (); system. out. println (Message); In. close (); socket. close ();}}

We know that this is a single thread and can only serve one client at a time. after Client A is connected, it is obtained by the server and the server executes the specific process. In this case, client B is connected and can only wait because the server has not processed the request of Client, what if many clients need to communicate with my server? It is best for the server to encapsulate each client in a different thread so that multiple client requests can be processed. Now we can implement multiple clients to upload files.
Public class tcpthreads implements runnable {private Socket socket; Public tcpthreads (Socket socket) {This. socket = socket;} public void run () {int COUNT = 1; string IP = socket. getinetaddress (). gethostaddress (); try {system. out. println (IP + "............ connected "); // obtain the client's input stream file = new file (IP + ". jpg "); // if the file already exists, modify the name to add one until the name is not equal to while (file. exists () file = new file (IP + "(" + (count ++) + ")" + ". Jpg "); inputstream is = socket. getinputstream (); // obtain the output stream outputstream out = socket of the client. getoutputstream (); // file storage location outputstream OS = new fileoutputstream (File); byte [] buffer = new byte [1024]; int Len = 0; while (LEN = is. read (buffer ))! =-1) {OS. write (buffer, 0, Len);} // feedback to the client bufferedwriter BW = new bufferedwriter (New outputstreamwriter (out); BW. write ("image uploaded"); BW. flush (); OS. close (); socket. close () ;}catch (exception e) {Throw new runtimeexception (IP + "Upload Failed ");}}}

 

Class clientimage {public static void main (string [] ARGs) throws exception {If (ARGs. length! = 1) {system. Out. println ("enter a valid file path"); return;} file = new file (ARGs [0]); If (! (File. exists () & file. isfile () {system. out. println ("this file already exists, or it is not a file"); return;} Long maxsize = 1024*1024*5; If (file. length ()> maxsize) {system. out. println ("file cannot exceed 5 m"); return;} If (! File. getname (). endswith (". jpg ") {system. out. println ("the file can only be jpg"); return;} // create a client service object Socket socket = new socket ("192.168.1.102", 12345 ); inputstream in = new fileinputstream (File); // obtain the output stream object outputstream OS = socket of the client. getoutputstream (); // obtain the input stream object inputstream of the client is = socket. getinputstream (); byte [] buffin = new byte [1024]; int Len = 0; while (LEN = in. read (buffin ))! =-1) {OS. write (buffin, 0, Len);} // tell the server that I have sent the socket. shutdownoutput (); bufferedreader BR = new bufferedreader (New inputstreamreader (is); string message = BR. readline (); system. out. println (Message); In. close (); socket. close ();}}

 

Class serverimage {public static void main (string [] ARGs) throws exception {serversocket Server = new serversocket (12345); While (true) {Socket socket = server. accept (); // blocking method. When a client object is obtained, a new thread (New tcpthreads (socket) is created )). start ();}}}

 

Now you can serve multiple clients. Check the server code. While (true) indicates that the server is always on,
Public static void main (string [] ARGs) throws exception {serversocket Server = new serversocket (12345); While (true) {Socket socket = server. accept (); // blocking method. When a client object is obtained, a new thread (New tcpthreads (socket) is created )). start ();}}

 

Because accept is a blocking method, when the client does not request the server, the server remains blocked until there is a client request. If multiple clients access the server, A new thread will also be created to serve the client, because the server processing code has been encapsulated into the run () method! Now we have implemented a small program similar to the above program, ----- tcp client concurrent login after reading the code written by the teacher, write it independently, always report some errors at the beginning, as long as you carefully analyze it, the problem can still be solved. If the teacher writes a line and you write a line, I think this is not a good result. I just tried it again, but I was not very impressed with it in my mind, if you write it independently, it may take several times, but it has already been integrated into your understanding and improved your ability to solve the problem. when I finish writing, compare it with the teacher, and then compare it better!
Class serverlogon implements runnable {private Socket socket; Public serverlogon (Socket socket) {This. socket = socket;} public void run () {string IP = socket. getinetaddress (). gethostaddress (); try {// print the client's ipsystem. out. println (IP + "............. connected! "); Bufferedreader BR = new bufferedreader (New inputstreamreader (socket. getinputstream (); printwriter PW = new printwriter (socket. getoutputstream (), true); // only chance of three attempts for (INT I = 0; I <3; I ++) {bufferedreader reader = new bufferedreader (New inputstreamreader (New fileinputstream ("user.txt"); string username = BR. readline (); // if the user exits directly if (username = NULL) {break;} string line = NULL; Boolean flag = False; while (line = reader. Readline ())! = NULL) {If (line. equals (username) {flag = true; break ;}// if the user name is the same if (FLAG) {system. out. println (username + "Logon successful"); PW. println ("Welcome to");} else {system. out. println (username + "try to log on"); PW. println ("invalid username");} reader. close ();} socket. close () ;}catch (ioexception e) {Throw new runtimeexception (IP + "connection failed ");}}}

 

Class userclient {public static void main (string [] ARGs) throws exception {Socket socket = new socket ("192.168.1.102", 11111); printwriter BW = new printwriter (socket. getoutputstream (), true); bufferedreader in = new bufferedreader (New inputstreamreader (socket. getinputstream (); bufferedreader BR = new bufferedreader (New inputstreamreader (system. in); For (INT I = 0; I <3; I ++) {string name = BR. readline (); system. out. println (name); // if the client presses Ctrl + CIF (name = NULL) break; BW. println (name); string message = in. readline (); system. out. println (Message); If (message. contains ("welcome") {break;} BR. close (); socket. close ();}}

 

public class TcpLogon {public static void main(String[] args) throws IOException {ServerSocket server = new ServerSocket(11111);while (true) {Socket socket = server.accept();new Thread(new ServerLogon(socket)).start();}}}

 

 

 

 

The user information is as follows:

 

We have written so many clients and servers. The general idea of a program, whether multi-thread or single-thread, remains unchanged. They are all used together with the stream. How complicated is the management server, the basic principle is as follows:

Learning this will help us understand and learn how to use web servers such as tomcat in the future!

 

-----------------
Java training Android training is expected to communicate with you ----------------------------

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.