TCP server development As an example--web developing different URL requests Why do you take different approaches

Source: Internet
Author: User

Take Java Web Development as an example, I believe there are many small partners to do the development of EE, HTPP request, JSON data transfer is often used in the work, query requests, add requests, modify the request front end with a URL, such as https://localhost/intsmaze/ User/add?name=intsmaze. The backend then builds a Controler class (Configure the URL mapping/user on the Class), and then creates a AddUser method (Configure the mapping/add on the method). Then launch the Web App, and the front-end send request will automatically go to the back-end AddUser method.

But do you know why this request goes the way of the corresponding? Let me take the example of a TCP-based service-side program in my big three period to see the rationale behind it. This program is a supermarket management system, the client uses javaswing writing, the server is written using Javase, the two sides of the communication using the TCP protocol, data stored in MySQL. The complete project is uploaded on GitHub.

Server-side startup class, bound port.
 Public classLoginserver {Private intport=1000; PrivateServerSocket ServerSocket; PrivateExecutorservice Executorservice; Private Final intpool_size=1;//the number of worker threads in a pool of CPU threads     PublicLoginserver ()throwsException {serversocket=NewServerSocket (); Serversocket.bind (NewInetsocketaddress ("127.0.0.1", port)); Executorservice=executors.newfixedthreadpool (Runtime.getruntime (). Availableprocessors () *pool_size); //Current number of CPUs * is the number of bus pools    }     Public voidService () { while(true) {Socket Socket=NULL; Try{Socket=serversocket.accept (); Executorservice.execute (NewHandler (socket)); }Catch(IOException e) {e.printstacktrace (); }        }    }         Public Static voidMain (string[] args)throwsException {Newloginserver (). Service (); }}
Path Mapping method

A different path behind localhost/intsmaze/is to intercept the corresponding string and call the corresponding method

 Public classHandlerImplementsrunnable{ Public Static Final intsolderconnection=0;//Shop assistant Login         Public Static Final intmanageraddsolder=7;//Admin Add Salesperson     Public Static Final intmanagerdeletesolder=8;//Admin Delete Salesperson     Public Static Final intmanagermoidfysolder=9;//Administrator modifies salesperson        Privatesocket socket; PrivateBufferedReader bufin=NULL; PrivateBufferedWriter bufout=NULL; PrivateConnection connection=NULL; PrivatePreparedStatement preparedstatement=NULL; PrivateResultSet resultset=NULL;  PublicHandler (Socket socket)throwsIOException { This. socket=socket; Bufin=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); Bufout=NewBufferedWriter (NewOutputStreamWriter (Socket.getoutputstream ())); }                 Public voidrun () {Try{String line=Bufin.readline (); //read the first selection function                intI=integer.valueof (line); Switch(i) { Casesolderconnection:solderconnection ();//Salesperson Login 0                             Break;  CaseManageraddsolder:manageraddsolder ();//Admin Add Salesperson 7                             Break;  CaseManagerdeletesolder:managerdeletesolder ();//Admin Delete Salesperson 8                             Break;  CaseManagermoidfysolder:managermodifysolder ();//Admin Modify Salesperson 9                             Break; }        }Catch(Exception e) {socketutil.close (socket); }        }                 Public voidSolderconnection ()throwsException {String sr=NULL; //read the account number and passwordString arr[] =bufin.readline (). Split ("#");; Connection=jdbcutil.getconnection (); PreparedStatement=connection.preparestatement ("SELECT * from solder WHERE solder_number=?") and solder_password=? "); Preparedstatement.setstring (1,arr[0]); Preparedstatement.setstring (2,arr[1]); ResultSet=Preparedstatement.executequery (); if(Resultset.next ()) {Bufout.write ("ok\n");//Feedback Query ConfidenceBufout.flush (); SR=resultset.getint (1) + "#" +resultset.getstring (2) + "#" +resultset.getstring (3) + "\ n";            Bufout.write (SR);                        Bufout.flush (); }            Else{bufout.write ("No");//Feedback Query ConfidenceBufout.flush ();        } jdbcutil.release (resultset, PreparedStatement, connection); }                             Public voidManageraddsolder ()throwsException {Connection=jdbcutil.getconnection (); String name=Bufin.readline ();            SYSTEM.OUT.PRINTLN (name); PreparedStatement=connection.preparestatement ("INSERT into solder (solder_name) VALUES (?)"); Preparedstatement.setstring (1, name); Preparedstatement.executeupdate ();//Perform the updatePreparedstatement=connection.preparestatement ("Select *from solder where solder_number= (select MAX (solder_number) From solder) "); ResultSet=preparedstatement.executequery ();//Perform the update            if(Resultset.next ()) {Bufout.write ("ok\n");//Feedback Query ConfidenceBufout.flush (); String Str=resultset.getstring (1) + "#" +resultset.getstring (2) + "#" +resultset.getstring (3); Bufout.write (str+ "\ n");//Feedback Query ConfidenceBufout.flush (); }            Else{bufout.write ("no\n");//Feedback Query ConfidenceBufout.flush ();        } jdbcutil.release (resultset, PreparedStatement, connection); }                 Public voidManagermodifysolder ()throwsException {Connection=jdbcutil.getconnection (); String arr[]=NULL; String Line=NULL; String Number=Bufin.readline (); PreparedStatement=connection.preparestatement ("Select *from solder WHERE solder_number=?")); Preparedstatement.setstring (1, number); ResultSet=Preparedstatement.executequery (); if(Resultset.next ()) {Bufout.write ("ok\n");//Feedback Query ConfidenceBufout.flush (); Line=Bufin.readline (); Arr=line.split ("#"); PreparedStatement=connection.preparestatement ("Update solder set solder_password=?,solder_name=?") WHERE solder_number=? "); Preparedstatement.setstring (1,arr[2]); Preparedstatement.setstring (2,arr[1]); Preparedstatement.setstring (3,arr[0]); Preparedstatement.executeupdate ();//Perform the update            }            Else{bufout.write ("no\n");//Feedback Query ConfidenceBufout.flush ();            } socket.close ();        Jdbcutil.release (resultset, PreparedStatement, connection); }                 Public voidManagerdeletesolder ()throwsException {Connection=jdbcutil.getconnection (); String Number=Bufin.readline (); PreparedStatement=connection.preparestatement ("Select *from solder WHERE solder_number=?")); Preparedstatement.setstring (1, number); ResultSet=Preparedstatement.executequery (); if(Resultset.next ()) {Bufout.write ("ok\n");//Feedback Query ConfidenceBufout.flush (); PreparedStatement=connection.preparestatement ("Delete from solder WHERE solder_number=?")); Preparedstatement.setstring (1, number); Preparedstatement.executeupdate ();//Perform the update            }            Else{bufout.write ("no\n");//Feedback Query ConfidenceBufout.flush ();            } socket.close ();        Jdbcutil.release (resultset, PreparedStatement, connection); }            }

The Localhost/intsmaze/user/add?name=intsmaze URL is used to reverse-parse how the TCP server receives and calls the corresponding method. LocalHost is the application that establishes a connection with the server and then sends Intsmaze/user/add?name=intsmaze as a data to the server, after the server receives the string, and then determines that the request is sent to Intsmaze. Then through the user knows this request when the user module (User Management Module), and then through add to know is called to add the users method. The following is the parameter to get into the database.

The above method can be improved as follows
String line=Bufin.readline (); //read the first selected function line value is Intsmaze/user/add?name=intsmazeString arr[]=line.split ("/"); String Model=arr[1]; String Method=arr[2].split ("?") [0]; String param=arr[2].split ("?") [1]; if(Model.endswith ("User"))                {                    if(Method.equals ("Add") {user.add (param); }                }                Else if(Model.equals ("goods"))                {                    ...                } Else if                ...

TCP server development As an example--web developing different URL requests Why do you take different approaches

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.