Home > other >  The Socket Tcpclient communication
The Socket Tcpclient communication

Time:09-18

I'm going to write a form in winform, using data from the serial port to accept lower machine, and then put it in an array, array through the socket communication to a steady stream of real-time communication is sent to the client (unity),
After opening the Form4, the service side open, listening to the client, run the Unity game (client), connect to the server, now at the ends of the connection can be connected, but not for data transfer, I think may be sending data interface function didn't sent out, or Unity is not received,
Tcpserver class defines the SendMsg method is used to send array,
Form4 cycle call SendMsg method after click the button to send data,
P1 is 2, 3 Form4 code
P4 5 Tcpserver class
P6 Unity (client)

CodePudding user response:

The method of receiving data
the Unity endPublic void ReceiveMessage IAsyncResult (ar)
{
List _byteData=https://bbs.csdn.net/topics/new List ();//create a byte queue
Bool start=false;
Try
{
//to empty errormessage
Error_Message="";
Int bytesRead;
BytesRead=this. _client. GetStream () EndRead (ar);
If (bytesRead & lt; 1)
{
return;
}
The else
{

for (int i=0; I & lt; BytesRead; I++)
{
If (start)
_byteData. Add (data [I]);
If (data [I]==35)//if read to # #, after will
byte in the queue{
Start=true;
}
Else if (data [I]==37)//if read %, converting the bytes in the queue to string in the temp
{
If (start)
{
String temp=Encoding. The ASCII. Get string (_byteData. ToArray (), 0, _byteData. Count - 1);
_byteData. The Clear ();
DataResolve (temp);//split string, for X, Y, the value of C
Temp="";//temp to empty, continue to look for the next number #
Start=false;
}
}



}
This. _client. GetStream (). BeginRead (data, 0, System. The Convert. ToInt32 (this) _client) ReceiveBufferSize), ReceiveMessage, null);
}
}
The catch (Exception ex)
{
Error_Message=ex. The Message;
}
}
  • Related