Java interacts with C

Source: Internet
Author: User
Tags sendmsg

/** * Java interacts with c * @param param send information * @return return information */public static map<string, string> infexchange (Object param) {map& Lt String, string> returnmsg = null; Socket socket = Null;dataoutputstream OutputStream = Null;datainputstream InputStream = null; String host = Null;int Port = 0;try{//Read address and port number host = Global.getconfig ("Socket.host");p ort = integer.valueof ( Global.getconfig ("Socket.port"));//Create socketsocket = new Socket (host, port); Socket.setsotimeout (20000);//timeout set to 20s The object is converted to Jsonobjectmapper mapper = new Objectmapper (); String json = mapper.writevalueasstring (param);//Front plus 4-bit length String sendmsg = Stringutils.padleft (string.valueof ( Json.getbytes ("GBK"). Length), ' 0 ', 4 + json; System.out.println ("delivery paper:" + sendmsg);//Send outputstream = new DataOutputStream (Socket.getoutputstream ()); O Utputstream.write (Sendmsg.getbytes ("GBK")); Outputstream.flush ();//Receive return InputStream = new DataInputStream ( Socket.getinputstream ()); byte[] B = new Byte[4];int count = 1;//reads only two times, reads the message length for the first time, reads the complete message for the second time (inputstream.read(b)!=-1) {if (count==1) {int len = integer.valueof (new String (b)); b = new byte[len];count++; Thread.Sleep (200);} Else{break;}} String response = new String (b, "GBK"); SYSTEM.OUT.PRINTLN ("return message:" + response);//Convert the JSON back to map format if (response!=null &&! "". Equals (response)) {returnmsg = Mapper.readvalue (response, Map.class);}} catch (Exception e) {e.printstacktrace ();} finally{//Close Stream try {inputstream.close (); Outputstream.close (); Socket.close ();} catch (IOException e) { E.printstacktrace ();}} return returnmsg;}

Java interacts with C

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.