[MonoDevelop] Using struct with socket C#

Leonel Florin Selles leonel06013 at cfg.jovenclub.cu
Sun Mar 27 16:04:27 EDT 2011


Hi friend:

Well I have a problem here, I'm creating a socket application that have a
server and a client, and they share information in form of struct, I mean,
the server send an struct to the client and the client work with that
information and forward this information in the same struct to the server,

I'm using the Marshal class to convert the struct into a byte[] and I
prove this between to different struct in the same program, but, when I
send the struct transform it in to byte[] to the client, it get the byte[]
but when i try to use the marshal class to restore the byte[] in to struct
the program closes without explanation, an example of what I'm doing

the struct I'm use

public struct cliente
	{
		public string clientName;
		public int clientPid;
		public string host;
		public string bd;
		public string user;
		public string pass;
		public string usersCheck;
		public bool systemTryIcon;
		public string adminpass;
		public signals orden;
	}

and the two method to convert struct to byte[], and byte[] to struct

public class dataManager
{
    public static byte[] structToByte (Object structura)
	{
        	int size = Marshal.SizeOf (structura);
		IntPtr apuntador = Marshal.AllocHGlobal (size);
		byte[] datos = new byte[size];

		Marshal.StructureToPtr (structura, apuntador, false);
		Marshal.Copy (apuntador, datos, 0, size);
		Marshal.FreeHGlobal (apuntador);

		return datos;
	}
     public static System.Object ByteToStruct (byte[] listaByte, Type
tipoStruct)
	{
		int size = Marshal.SizeOf (tipoStruct);
		if (size > listaByte.Length)
			return null;
		IntPtr apuntador = Marshal.AllocHGlobal (size);
		System.Object objeto = new Object ();

		Marshal.Copy (listaByte, 0, apuntador, size);
		objeto = Marshal.PtrToStructure (apuntador, tipoStruct);
		Marshal.FreeHGlobal (apuntador);

		return objeto;
	}
}

and using Socket to create the server and to conect the client

the server

Socket socketServer = new Socket (AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
socketServer.Bind (new IPEndPoint (IPAddress.Any, puerto));
socketServer.Listen (100);

the client

ocket cliente = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.IP);
cliente.Connect ("localhost", 4069);

//converting the struct to byte[]......

cliente.Send (sendData, 0, sendData.Length, SocketFlags.None);


what can you tell my about?



More information about the Monodevelop-list mailing list