"Urgent" C # Server with the socket and Android service-side interoperability training, to two-way, I wrote a, unsuccessful, seeking examples, guidance, urgent AH

Source: Internet
Author: User


==================== Problem Description ====================
C # Service side:
 //Create a listening port ...  private void startlistening ()          {              //Creating IPEndPoint             ipendpoint ipep = new  ipendpoint (Ipaddress.parse ("192.16.41.120"),  8897);               //creating a Socket instance            Server_socket = new socket (addressfamily.internetwork, sockettype.stream,  PROTOCOLTYPE.TCP);             // Bind sockets with Ipendpoint           server_socket.bind (IPEP);              //Set Socket listening mode             servEr_socket.listen (+);            while  (true)             {                 try                 {                     system.net.sockets.socket s =  server_socket.accept ();                     thread newsocekt= new thread (new  Parameterizedthreadstart (serviceclient));                     newsocekt. Start (s);                }                 catch  (exception e)                  {                     console.writeline (E.tostring ());                 }             }        }         Open a new thread for each socket connected to the server         private void serviceclient ( OBJECT SOC)         {             System.Net.Sockets.Socket clientS = soc as Socket;             byte[] bytearry = new byte[1024];             int buffer_lenght =  Clients.available;            clients.receive ( Bytearry, 0, buffer_lenght, socketflags.none);//Get messages from Android, here you can get information              string res = encoding.getencoding ("Utf-8"). GetString (Bytearry);            //******             *****/             // res  is the message from Android, what to do with info, omitted here             byte[] arry = encoding.getencoding ("Utf-8"). GetBytes ("I screw your uncle, give me a message back/0");     &nbsP;      clients.send (Arry, arry. Length, socketflags.none);//Send a message back to Android            // I feel that this is not quite right, so that the client to C # can receive, but android that can't get         }


Service side
Public class socketclient {static socket client;public socketclient (String  Site, int port)  {try {client = new socket (site, port);}  catch  (exception e)  {log.i ("t460470591",  "error"); E.printstacktrace ();}  }public string sendmsg (string msg)   {try {printwriter out;out =  new printwriter (New bufferedwriter (New outputstreamwriter (Client.getOutputStream ())),  true); out.println (msg);//Send data to server                          thread.sleep (1000);// Do not do While loop receive server data, I just sleep a bit, only receive once data  inputstream inputstream=  client.getinputstream ();  //gets the input stream of the socket bytearrayoutputstream   baos   =   new    bytearrayoutputstream ();      &nBsp;   int   i=-1;         while ((i =inputstream.read ())!=-1) {  //I debug found here, every time there is data, I followed while, a f6,f6 press,//press the right here to die ... Not my machine, I do not know how to do, anyway, the data will not come back, the program is not wrong,//and directly can not debug, it is estimated that is still in the data         baos.write (i);          }   LOG.I ("t460470591",  Baos.tostring ());//Gets the received value here, but the program is blocked here   return baos.tostring ();}  catch  (exception e)  {e.printstacktrace (); LOG.I ("t460470591", E.getmessage () +  "a");} return  "";}

Socket I was the first time to write, a lot of do not understand, and still boast platform, a good-looking, ah, for help, have a look
==================== Solution 1====================
Java Side Two issues
1. static Socket client; Use in the instance method and do not synchronize, remove static, or the multi-threaded send is all messed up
2. Service side because you have used a separate thread processing, so write a read with blocking execution will not have any effect, the client sent directly in the main thread in the synchronous send and then read it is not advisable to send to receive, you use Thread.Sleep (1000); How are you sure of this time?

The common practice in C # is to asynchronously send and read BeginSend (datas, Onreadreplaycallback, Stateobj)
void Onreadreplaycallback (IAsyncResult asyncResult)
{
while (read to data) write cache
If (the cache is not empty) triggers an event or delegate that receives data
}
This way, the program does not have to be blocked, and it is executed correctly in sequence.
The above is just a thought for reference.

"Urgent" C # Server with the socket and Android service-side interoperability training, to two-way, I wrote a, unsuccessful, seeking examples, guidance, urgent AH

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.