Java Small Project Point meal System (ii) service side

Source: Internet
Author: User

Service Solution:

The main function of the server is to listen to a port number indefinitely, respond to the connection request from the client, and then open a new thread to process the client. The interface is relatively simple to display online users, divided into businessmen and students.


I. Listening for socket connection requests from clients

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >package mainjframe;import java.awt.dimension;import Java.awt.gridlayout;import java.awt.Toolkit;import Java.awt.event.windowadapter;import Java.awt.event.windowevent;import Java.io.ioexception;import Java.net.serversocket;import Java.net.socket;import Java.util.linkedlist;import Javax.swing.JFrame;import Javax.swing.jscrollpane;import Javax.swing.jtable;import Javax.swing.table.defaulttablemodel;public Class MainWindow extends Jframe{serversocket server; JTable user_table; JTable seller_table; JScrollPane User_jscrollpane; JScrollPane Seller_jscrollpane;defaulttablemodel User_model;defaulttablemodel Seller_model; String []user_headers = {"Serial number", "online Student"}; String []seller_headers = {"Serial number", "Online merchant"};object [][]celldata=null; Linkedlist<user> Student,seller; linkedlist<socket> mysocket;public static void Main (String args[]) {New MainWindow ("service Side");} Public MainWindow (String s) {super (s); student = new linkedlist<user> (); seller = nEW linkedlist<user> (); mysocket = new linkedlist<socket> (); Addwindowlistener (new Windowadapter () {public void Windowclosing (WindowEvent e) {Dispose (); System.exit (0);});    /Get screen size Dimension screensize =toolkit.getdefaulttoolkit (). Getscreensize ();    Set the position and size of the form setbounds ((screensize.width-320)/2, (screensize.height-240)/2,320,240);    SetLayout (New GridLayout ());    User_model = new DefaultTableModel (celldata,user_headers);    user_table = new JTable (User_model);    Seller_model = new DefaultTableModel (celldata,seller_headers);    seller_table = new JTable (Seller_model); User_jscrollpane = new JScrollPane (user_table); User_jscrollpane.setpreferredsize (new Dimension); Seller_ JScrollPane = new JScrollPane (seller_table); Seller_jscrollpane.setpreferredsize (new Dimension); Add (user_ JScrollPane); add (Seller_jscrollpane); setvisible (true); validate (); StartServer ();} void Update () {user_model.setrowcount (0); Seller_model.setrowcount (0); for (int i=0;i<student.size (); i++) {User_model.addrow (new Object[]{i+1,student.get (i). account}); for (int i=0;i<seller.size (), i++) {Seller_model.addrow (new Object[]{i+1,seller.get (i). account});}}          void StartServer () {int i = 0;              try {//Set listening port number and maximum number of accesses server = new ServerSocket (8889, 3);             System.out.println ("==========start=========== Come on!");            New Thread (New Listenthread (this)). Start ();                  while (true) {Socket socket = server.accept ();                Mysocket.add (socket);                  i++; System.out.println ("First" + i + "User connected successfully!                 ");                System.out.println ("The address information for this client is:" +socket.getinetaddress ());              New Thread (New Serverthread (Socket,this)). Start ();          }} catch (IOException e) {e.printstacktrace (); }}}class Listenthread implements Runnable{private MainWindow mainwindow;public listenthread (MainWindow MainWindow) {This.mainwindow = MainWindow;} PubLIC void Run () {while (true) {for (int i=0;i<mainwindow.mysocket.size (); i++) {if (MainWindow.mysocket.get (i). IsClosed ()) {for (int j=0;j<mainwindow.student.size (); j + +) {if (MainWindow.student.get (i). Address = = MainWindow.mysocket.get (i). Getinetaddress ()) MainWindow.student.remove (MainWindow.student.get (i)); for (int j=0;j<mainwindow.seller.size (); j + +) {if (MainWindow.seller.get (i). Address = = MainWindow.mysocket.get (i). Getinetaddress ()) MainWindow.seller.remove (MainWindow.seller.get (i)); Mainwindow.update (); MainWindow.mysocket.remove (MainWindow.mysocket.get (i)); SYSTEM.OUT.PRINTLN ("Client has been disconnected");}} Try{thread.sleep (500);} catch (Exception e) {}}}}</span>
a while loop is used in the process to continuously listen for requests made by the client, and once the request is established, a new Serverthread child thread is created to process the client's request while the main thread continues to wait. Also open up a listenthread thread to constantly determine which thread has been disconnected.

two. Processing of client requests in Serverthread

<span style= "FONT-FAMILY:KAITI_GB2312;FONT-SIZE:18PX;" >package mainjframe;import java.io.datainputstream;import Java.io.dataoutputstream;import java.io.IOException;    Import Java.net.socket;public class Serverthread implements Runnable {private socket socket;    Private String accept;    String account,passwd;    DataInputStream in = null;    DataOutputStream out = null;    Linkmysql Linkmysql;    String Dept; Private MainWindow mainwindow;//Create static global variable public serverthread (Socket Socket,mainwindow MainWindow) {THIS.M        Ainwindow = MainWindow;          This.socket = socket;    Linkmysql = new Linkmysql (this); }//The task is to provide a service to a user @Override public void run () {try {//Read the data that the client passed over the information              InputStream in = new DataInputStream (Socket.getinputstream ());               Send information to the client dataoutputstream out = new DataOutputStream (Socket.getoutputstream ()); System.out.println ("Put the horse over!!!!"   ");         Read information from the client accept = In.readutf ();        System.out.println (accept);          } catch (IOException e) {e.printstacktrace ();                  } if (Accept.equals ("LOGIN")) {try {account = In.readutf ();                 passwd = In.readutf ();                 System.out.println ("User name:" +account+ "\ n Password:" +passwd); for (int i=0;i<mainwindow.student.size (); i++) {if (Account.equals (mainWindow.student.get                (i). account) {socket.close (); }} for (int i=0;i<mainwindow.seller.size (); i++) {if (AC                Count.equals (MainWindow.seller.get (i). account)) {socket.close ();                 }} Dept = Linkmysql.query (ACCOUNT,PASSWD);                 OUT.WRITEUTF (dept); if (Dept. Equals ("Student")) {User temp = new User ();                 Temp.account = account;                 TEMP.PASSWD = passwd;                 Temp.type = "Student";                 Temp.address = Socket.getinetaddress ();                 MainWindow.student.add (temp);                 Mainwindow.update ();                 Linkmysql.initstudent (in,out);                                  Linkmysql.handleorder ();                 } else if (dept.equals ("seller")) {User temp = new User ();                 Temp.account = account;                 TEMP.PASSWD = passwd;                 Temp.type = "Seller";                 Temp.address = Socket.getinetaddress ();                 MainWindow.seller.add (temp);                 Mainwindow.update ();                 Linkmysql.initseller (in,out); }} catch (IOException e) {}} else if (Accept.equals ("REGISTER")) {}}} </span> 
first read the request from the client, and then enter the corresponding function module, if the user is logged in, then the SQL statement operation and response to the results, if the query is wrong to close the thread, the student is to join the student linked list and initialize the student's product information and store information, Judgment for the merchant will change the merchant's product information sent past and find the corresponding order form, the business belongs to the order of the merchant.

The main function of the server is to use sockets and multithreading to connect students and merchants, and all the operation of the data in the service side to do, all by the server and the database to interact, to ensure the security of data.

Java Small Project Point meal System (ii) service side

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.