C # send a command to a specified device and receive the data it returns

Source: Internet
Author: User

Network Programming is really troublesome, so it is hard to remember.

 

Private void mybutton#click (Object sender, eventargs e) <br/>{< br/> // establish a connection to send messages <br/> system. net. sockets. tcpclient TCP = new system. net. sockets. tcpclient ("192.168.24.23", 8051); <br/> string signal = "create Param" + "/R/N"; <br/> byte [] DATA = encoding. ASCII. getbytes (signal); <br/> networkstream stream = NULL; <br/> try <br/> {<br/> stream = TCP. getstream (); <br/> stream. write (data, 0, Data. length); <br/>}< br/> catch (exception ee) <br/>{< br/> console. writeline (EE. tostring (); <br/>}< br/> finally <br/> {<br/> // TCP. close (); <br/>}</P> <p> // take a 5-second break and wait for the returned value <br/> thread. sleep (5000); <br/> policyrecieved storerecievedstr = new policyrecieved (storereceivedstr); <br/> const int size = 1024*5; <br/> byte [] readbuffer = new byte [size]; <br/> int readtop = 0; </P> <p> system. net. sockets. networkstream ns; </P> <p> NS = TCP. getstream (); </P> <p> int getbyte = NS. read (readbuffer, readtop, size-readtop); </P> <p> byte [] tempbyte = new byte [getbyte]; <br/> for (INT I = 0; I <getbyte; I ++) <br/>{< br/> tempbyte [I] = readbuffer [I]; <br/>}</P> <p> byte [] unibytes = encoding. convert (ecsjis, ecuni, tempbyte); <br/> storerecievedstr. invoke (ecuni. getstring (unibytes); </P> <p> thread. sleep (1000); </P> <p> MessageBox. show ("result data ---->" + rsbuffer); <br/>}</P> <p> encoding ecuni = encoding. getencoding ("UTF-16"); <br/> encoding ecsjis = encoding. getencoding ("shift-JIS"); <br/> volatile protected string rsbuffer = ""; </P> <p> delegate void policyrecieved (string text ); </P> <p> Public void storereceivedstr (string rstr) <br/>{< br/> // This Is A delegate function <br/> lock (rsbuffer) <br/>{< br/> rsbuffer + = rstr; <br/> console. writeline (rstr); <br/>}< br/>}

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.