Add a socket to your Web project (enhanced version)

Source: Internet
Author: User

Long connections:

package com.sichang.util;import java.io.bufferedreader;import java.io.ioexception;import  java.io.inputstream;import java.io.inputstreamreader;import java.io.outputstream;import  java.io.printwriter;import java.net.serversocket;import java.net.socket;import  java.text.simpledateformat;import java.util.arraylist;import java.util.date;import  java.util.list;import java.util.stringtokenizer;import java.util.regex.matcher;import  java.util.regex.pattern;import org.json.jsonarray;import org.json.jsonexception;import  Org.json.jsonobject;import com.sichang.dao.dbbase;import com.sichang.dao.dbservice;public class  server_socket2 {static dbservice db = dbbase.getinstance ();//  instantiation daostatic  responseutil responseutil = new responseutil ();p ublic void  Startsocketservice () {Serversocket serversocket = null;while (True) {        try        {         if (serversocket == null) {         serversocket = new serversocket (9090);}         else        {         socket socket = serversocket.accept ();                          //main thread Get client connection              Thread workthread = new thread (New handler (socket));     //Create thread             workthread.start ();                                      //Start Thread         }         }        catch (exception e)          {             E.printstacktrace ();         }}}class handler implements  Runnable{    private Socket socket;    public  Handler (Socket socket)     {         this.socket=socket;    }         @SuppressWarnings ( "Unchecked") Public void run ()     {    try         { &nbsP;  while (socket.isconnected ())     {    BufferedReader  br = null; printwriter pw = null;             SYSTEM.OUT.PRINTLN ("New Connection:" +socket.getinetaddress () + ":" +socket.getport ());             socket.setsotimeout (;inputstream in = ) Socket.getinputstream (); Inputstreamreader is = new inputstreamreader (in);br =  New bufferedreader (IS); String info = br.readline (); System.out.println ("9090:"  + info); string switchstate =  "";if  (info != null)  {//  driving track if  ( Info.contains ("Pathhistory")) {//  handles the passed-over string list<string> list = string2list (info);         //  Call Insert Lane path method          insertpathhistoRY (list);/******************** query switch status data to device ***********************/         string imsi = responseutil.beequal (List.get (1). toString ());         string selectswitchstateok = db.selectswitchstate (IMSI). toString (); Switchstate = jsonresolvearray (Getrowsdata (Selectswitchstateok),  "#");}   Heartbeat Packet if  (Info.contains ("Tick"))  {/******************** query the switch state data to the device ***********************///   handles the string passed over List<string> list = string2list (info);                 String IMSI =  Responseutil.beequal (List.get (1). ToString ()); String selectswitchstateok = db.selectswitchstate (IMSI). toString (); Switchstate = jsonresolvearray (Getrowsdata (Selectswitchstateok),  "#");}   Device Registration if  (info.contains ("Deviceregister"))  {//  handling passed-over charactersString List<string> list = string2list (Info);         Switchstate = deviceregister (list);} Outputstream out = socket.getoutputstream ();p W = new printwriter (out);p W.print ( SwitchState);//pw.print ("\ n");p W.flush ();} Else{break;}   Close//in.close ();//is.close ();//br.close ();////out.close ();//pw.close (); Thread.Sleep (;        }    }   )  catch (exception e)     {         E.printstacktrace ();        }    finally     {    if (socket.isclosed ()  == false)     {     try{socket.close ();}  catch  (ioexception e) {// todo auto-generated catch blocke.printstacktrace ( );}    &nbsP;}     }    }}/** *  remove the data in front of the =  equals sign  *  @param   data *  @return  *  @throws  exception */public static string beequal (String data) {string dest =  ""; Pattern p = pattern.compile (". *="); Matcher m = p.matcher (data);d Est = m.replaceall ("");//system.out.println ("processed character =" + dest); return dest;}   Converts a string to List@suppresswarnings ("Rawtypes") public static list string2list (String info {//  handles the string passed over list<string> list=new arraylist<string> ();         stringtokenizer st=new stringtokenizer (Info, "&");         while (St.hasmoretokens ()) {         List.add (St.nexttoken ());         }return list;}   Parsing JSON array 2PUBLIC&NBSp;static string jsonresolvearray (STRING&NBSP;RESPONSESTR,&NBSP;STRING&NBSP;DIVIDESTR)  {String  returnArrayStr =  ""; Jsonarray arr = null;try {arr = new jsonarray (RESPONSESTR);for  (int  i = 0; i < arr.length ();  i++)  {JSONArray temp =  ( Jsonarray)  arr.get (i);// if  (!temp.getstring (i). Equals (""))// {for  (int j =  0; j < temp.length ();  j++)  {returnarraystr += temp.getstring (j)  + dividestr;}  }}} catch  (exception e)  {e.printstacktrace ();} Return returnarraystr;}   Device Registration @suppresswarnings ("Rawtypes") Public static string deviceregister (List list) { String switchstate= "";        string imsi =  Responseutil.beequal (List.get (1). ToString ()); string selectdeadlineok = d B.selectdeadline (IMSI). ToString (), if (Getresultdata (Selectdeadlineok). Equals ("OK")) {String deadline  = jsonresolvearray (Getrowsdata (Selectdeadlineok), ""); if (Deadline.equals ("null")  | |   "". Equals (Deadline) {//  start initializing Simpledateformat df = new simpledateformat (" Yyyy-mm-dd hh:mm:ss ");//Set Date format String created = df.format (New date ()); STRING&NBSP;UPDATESIM_IDOK&NBSP;=&NBSP;DB.UPDATESIM_ID (imsi, created, "a"). ToString ();//  Initialize if ( Getresultdata (Updatesim_idok). Equals ("OK") {//  here also add affection number   familynumberswitchstate= Responseutil.getserviceinfo () + "#" +familynumber (IMSI) + "#";} ELSE{SYSTEM.OUT.PRINTLN ("Initialization Failed");}} else{//  query out IMSI information sent to client Switchstate=responseutil.getserviceinfo () + "#" +familynumber (IMSI) + "#";}} Else{system.out.println (Selectdeadlineok);} Return switchstate;}   Get affection number Public static string familynumber (String imsi) {String familynumber  =  ""; String famIlynumberok = db.familynumber (IMSI). toString (); if (Getresultdata (Familynumberok). Equals ("OK") { Familynumber = jsonresolvearray (Getrowsdata (Familynumberok), "");if  (FamilyNumber.length () <1)  {familyNumber =  "null";}} Else {}return familynumber;}   Insert Database @suppresswarnings ("Rawtypes") public static void insertpathhistory (List list) { String imsi = responseutil.beequal (List.get (1). toString ());         string sendtime = responseutil.beequal (List.get (2). toString ()). ReplaceAll ("T", "   "); string tablename =  "Z_" +responseutil.tailtime (sendtime); String positions = responseutil.beequal (List.get (3). ToString ()); String speed = responseutil.beequal (List.get (4). ToString ()); System.out.println ("imsi  " +imsi); System.out.println ("sendtime  " +sendtime); System.out.println ("tablename   " +taBlename); System.out.println ("positions" +  positions); System.out.println ("speed  " +speed);//  determines whether the database table exists, if any, inserts if not, creates if (Judgetable (tableName)) {//   Insert Database Db.insertthatdaytable (Tablename, imsi, sendtime, coursedata (positions),  speed). ToString ();} else{//  Create the database and insert Data string createtableok = db.createtable (tableName). toString (); Getresultdata (Createtableok). Equals ("OK") {//system.out.println ("create successfully, start inserting");d b.insertthatdaytable (TableName,  imsi, sendtime, coursedata (positions),  speed). toString ();} Else{system.out.println ("Creation failed:" +createtableok);}}}   method to remove the value of the result node Public static string getresultdata (string data)  {//  Start fetching data from the result node jsonobject jsonderice;object dericeobject = null;try {jsonderice  = new jsonobject (data);d ericeobject = jsonderice.get ("result");}  catch  (jsonexception e)  {// todo auto-generated catch blocke.printstacktrace ();} Return dericeobject.tostring ();}   Determine if a database table exists public static boolean judgetable (string date) {String judgetableok  = db. Judgetable (date). toString (); System.out.println ("judgetableok     " +judgetableok); String rowsdata = jsonresolvearray (Getrowsdata (judgetableok),  ""); System.out.println (Rowsdata); if ("". Equals (Rowsdata)) {//  no table return false;} else{//  has table return true;}}   Processing of the uploaded data 2public static string coursedata (string positions) {string str= ""; String[] positions=positions.split ("\\/");for  (int i = 0; i <  positions.length; i++)  {string[] positionss = positions[i].split (","); str += Responseutil.bigdeci (Double.parsedouble (Positionss[0])) + "," +responseutil.bigdeci (Double.parsedouble (positionSs [1])) +"|";}  system.out.println ("track with over-precision"+str"); return str;}   method to remove values of rows node Public static string getrowsdata (string data)  {JSONObject  Jsobj;object pesobj = null;try {jsobj = new jsonobject (data);p esobj =  jsobj.get ("Rows");}  catch  (jsonexception e)  {// TODO Auto-generated catch  Blocke.printstacktrace ();} Return pesobj.tostring ();}}





Add a socket to your Web project (enhanced version)

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.