Java Project file synchronization solution on different servers (socket, HTTP)

Source: Internet
Author: User

The need to do data synchronization between the last two projects, the request is a project data and picture files to synchronize to the B project, first two projects are independent of the project to collect input information, database data synchronization does not say, there are some pictures and other files need to be synchronized, the first thought is the B project call a project picture path, Because the picture file path of two projects has many kinds of generation situation, two projects are running, this kind of picture path method is ruled out. There are two ways to solve this:

The 1 socket method is to start when the B project is added to the Listen B project, using the client in the A project.

2 Submit to Project B through the HttpURLConnection analog post form in a project. (Personal feeling this is better)

HttpURLConnection:

Package Test.httpup;import Java.io.bytearrayoutputstream;import Java.io.dataoutputstream;import java.io.File; Import Java.io.fileinputstream;import Java.io.inputstream;import Java.net.httpurlconnection;import Java.net.sockettimeoutexception;import Java.net.url;import Java.net.urlencoder;import Java.util.HashMap;import Java.util.iterator;import Java.util.map;import Java.util.set;import Javax.imageio.imageio;import Javax.imageio.imagereader;import javax.imageio.stream.imageinputstream;public class HttpPostUtil {URL url; HttpURLConnection Conn; String boundary = "--------http"; map<string, string> textparams = new hashmap<string, string> (); map<string, file> fileparams = new hashmap<string, file> ();D ataoutputstream ds;public HttpPostUtil (String    URL) throws Exception {this.url = new URL (URL);} Reset the server address to be requested, that is, the address of the uploaded file.    public void SetUrl (String url) throws Exception {this.url = new URL (URL);} Add a normal string data to form form data in public void Addtextparameter (string name, string VALue) {textparams.put (name, value);}    Add a file to form form data in public void Addfileparameter (String name, File value) {fileparams.put (name, value);}    Clears all added form form data public void Clearallparameters () {textparams.clear (); Fileparams.clear ();} Sends data to the server, returns an array of bytes containing the returned results of the server public byte[] Send () throws Exception {initconnection (); try {conn.connect ();} catch ( Sockettimeoutexception e) {//Somethingthrow new RuntimeException ();} ds = new DataOutputStream (Conn.getoutputstream ()); Writefileparams (); Writestringparams ();p aramsend (); InputStream in = Conn.getinputstream (); Bytearrayoutputstream out = new Bytearrayoutputstream (), int b;while ((b = In.read ())! =-1) {out.write (b);}    Conn.disconnect (); return Out.tobytearray ();} Some of the files uploaded by connection must be set to private void Initconnection () throws Exception {conn = (httpurlconnection) This.url.openConnection (); Conn.setdooutput (true); Conn.setusecaches (false); Conn.setconnecttimeout (10000); The connection timeout is 10 seconds conn.setrequestmethod ("POST"); Conn.setrequestproperty ("Content-typE "," multipart/form-data;    boundary= "+ boundary);} Normal string data private void Writestringparams () throws Exception {set<string> KeySet = Textparams.keyset (); for ( Iterator<string> it = Keyset.iterator (); It.hasnext ();) {String name = It.next (); String value = textparams.get (name);d s.writebytes ("--" + boundary + "\ r \ n");d s.writebytes ("Content-disposition: Form-data;    Name=\ "+ name+" \ "\ r \ n");d s.writebytes ("\ r \ n");d s.writebytes (Encode (value) + "\ r \ n");}} File Data private void Writefileparams () throws Exception {set<string> KeySet = Fileparams.keyset (); for (iterator< String> it = Keyset.iterator (); It.hasnext ();) {String name = It.next (); File value = fileparams.get (name);d s.writebytes ("--" + boundary + "\ r \ n");d s.writebytes ("Content-disposition: Form-data; Name=\ "" + name+ "\"; Filename=\ "" + Encode (Value.getname ()) + "\" \ \ r \ n ");d s.writebytes (" Content-type: "+ getcontenttype (value) +" \ r \ n ");    Ds.writebytes ("\ r \ n");d S.write (getBytes (value));d s.writebytes ("\ r \ n");} BeenFile upload type, image format is image/png,image/jpg and so on. Non-picture is application/octet-streamprivate String getContentType (File f) throws Exception {//return "application/  Octet-stream "; This line no longer subdivides whether it is a picture, all as Application/octet-stream type Imageinputstream ImageIn = Imageio.createimageinputstream (f); ImageIn = = null) {return ' Application/octet-stream ';} Iterator<imagereader> it = imageio.getimagereaders (ImageIn); if (!it.hasnext ()) {imagein.close (); return " Application/octet-stream ";} Imagein.close (); return "image/" + it.next (). Getformatname (). toLowerCase ();//Convert the value returned by FormatName to lowercase, default to uppercase}// Convert the file to a byte array private byte[] GetBytes (file f) throws Exception {FileInputStream in = new FileInputStream (f); Bytearrayoutputstream out = new Bytearrayoutputstream (); byte[] B = new Byte[1024];int N;while ((n = in.read (b))! =-1) {OU T.write (b, 0, n);} In.close (); return Out.tobytearray ();} Add end Data private void Paramsend () throws Exception {ds.writebytes ("--" + Boundary + "--" + "\ r \ n");d s.writebytes ("\ r \ n");} The string containing the Chinese is transcoded, which is UTF-8. Server over there toTo decode the private string encode (string value) throws exception{return Urlencoder.encode (value, "UTF-8"); }public static void Main (string[] args) throws Exception {httppostutil u = new Httppostutil ("Http://xxxxxx.action"); U.add Textparameter ("Path", "qs/"), U.addtextparameter ("FileName", "111.jpg"), U.addfileparameter ("Picfile", New File ("d:/ /272.jpg ")); U.addtextparameter (" Text "," Utf-8 "); byte[] B = u.send (); string result = new String (b); SYSTEM.OUT.PRINTLN (result);}}
=====================
Socket Client

Package Test.socket;import Java.io.dataoutputstream;import Java.io.file;import java.io.fileinputstream;import Java.io.ioexception;import java.net.inetsocketaddress;import Java.net.socket;import java.net.URL;/** * File sending client main program * @ Author Admin_hzw * */public class Bxclient {/** * Program Main method * @param args * @throws ioexception */public static void Main (S Tring[] args) throws IOException {int length = 0;double SumL = 0; byte[] sendbytes = null; Socket socket = Null;dataoutputstream DOS = null;  FileInputStream FIS = null;boolean bool = false;try {File File = new file ("D:/272.jpg");//file path to transfer long L = File.length ();  Socket = new socket (); Socket.connect (New Inetsocketaddress ("192.168.1.110", 8877));d OS = new DataOutputStream (Socket.getoutputstream ());      FIS = new FileInputStream (file);  Sendbytes = new byte[1024];  while (length = Fis.read (sendbytes, 0, sendbytes.length)) > 0) {sumL + = length; SYSTEM.OUT.PRINTLN ("Transmitted:" + ((suml/l) *100) + "%");d os.write (sendbytes, 0, length);d Os.flush ();} Although the data classType is different, but Java is automatically converted to the same data type after doing comparison if (suml==l) {bool = true;}}  catch (Exception e) {System.out.println ("Client file transfer exception"); bool = False;e.printstacktrace ();   finally{if (dos! = null) dos.close (); if (FIS! = null) fis.close ();    if (socket! = NULL) socket.close (); }SYSTEM.OUT.PRINTLN (bool? ") Success ":" Failed ");}}
Socket server

Xml

<listener>    <listener-class>XXX.web.listener.SocketServiceLoader</listener-class>  </listener>  

Import Javax.servlet.servletcontextevent;import Javax.servlet.servletcontextlistener;public class Socketserviceloader implements Servletcontextlistener {//socket server thread      private socketthread socketthread;            @Override public      void contextdestroyed (Servletcontextevent arg0) {          if (null!=socketthread &&! Socketthread.isinterrupted ())          {           socketthread.closesocketserver ();           Socketthread.interrupt ();          }   }        @Override public      void contextinitialized (Servletcontextevent arg0) {          //TODO auto-generated method stub          if (null==socketthread)          {           //New Thread class           socketthread=new socketthread (null);           Start thread           socketthread.start ();}}}  

Import Java.io.ioexception;import Java.net.serversocket;import Java.net.socket;public class SocketThread extends            thread{private ServerSocket serversocket = null; Public Socketthread (ServerSocket serverscoket) {try {if (null = = ServerSocket) {thi                  S.serversocket = new ServerSocket (8877);              SYSTEM.OUT.PRINTLN ("socket start");              }} catch (Exception e) {System.out.println ("Socketthread Create socket Service error");          E.printstacktrace ();  }} public void Run () {while (!this.isinterrupted ()) {try {Socket                                    Socket = Serversocket.accept (); if (null! = Socket &&!socket.isclosed ()) {//Processing accepted data new Socketoperate                  (socket). Start ();                                } socket.setsotimeout (30000);      }catch (Exception e) {            E.printstacktrace (); }}} public void Closesocketserver () {try {if (Null!=serversocket &am              p;&!serversocket.isclosed ()) {serversocket.close ();         }} catch (IOException e) {//TODO auto-generated catch block E.printstacktrace (); }       }              }

Import Java.io.datainputstream;import java.io.file;import java.io.fileoutputstream;import java.io.IOException;            Import Java.net.socket;import Java.util.random;public class Socketoperate extends thread{private socket socket;      Public socketoperate (socket socket) {this.socket=socket; } @SuppressWarnings ("unused") public void Run () {try{System.out.println ("Start listening ...");/* * If you do not have access to it will automatically wait for */system.out.println ("link"); Receivefile (socket);}       catch (Exception e) {System.out.println ("server Exception"); E.printstacktrace ();} }/*public void Run () {}*//** * Receive file Method * @param socket * @throws ioexception */public static void Receivefile ( Socket socket) throws IOException {byte[] inputbyte = null;int length = 0;datainputstream dis = null; FileOutputStream fos = null; String FilePath = "d:/temp/" +new Random (). Nextint (10000) + ". jpg"; try {try {dis = new DataInputStream ( Socket.getinputstream ());  File F = new file ("D:/temp"), if (!f.exists ()) {F.mkdir (); }/* * File storage location */fos = new FileOutputStream (new file (FilePath));   Inputbyte = new byte[1024];  System.out.println ("Start receiving data ...");    while (length = Dis.read (inputbyte, 0, inputbyte.length)) > 0) {fos.write (inputbyte, 0, length); Fos.flush (); }SYSTEM.OUT.PRINTLN ("Complete reception:" +filepath);} finally {if (FOS! = null) fos.close (); if (dis! = null) dis.close (); if (socket! = NULL) Socket.close ();}}   catch (Exception e) {e.printstacktrace ();}}}



Java Project file synchronization solution on different servers (socket, HTTP)

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.