C # Socket Get started 4 UPD send fabric body (GO)

Source: Internet
Author: User

Today we're going to learn how to send a socket structure

1. First look at the structure to be sent

UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.Text;
UsingSystem.Runtime.InteropServices;

NamespaceLin.p2p.Mo
{
///<summary>
///Communication Message Format
///</summary>
[Serializable]
[StructLayout (LayoutKind.Sequential, Pack= 1)]
public struct cp2pmessage
{
public sbyte nmessagetypes;
public int Value;
}
}

2. Please look at the server

UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.Text;
UsingSystem.Net.Sockets;
UsingSystem.Net;
Usinglin.p2p;
UsingLin.p2p.Mo;

NamespaceConsoleApplication1
{
ClassProgram
{
StaticvoidMain (String[] args)
{
//1. Create a nested section word
Socket socket=NewSockets (AddressFamily.InterNetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);

//2. Fill the IP
IPEndPoint Ipe=NewIPEndPoint (Ipaddress.any,4321);

//3. Binding
Socket. Bind (IPE);

//Waiting for the client to connect
Console.WriteLine ("This is a Server with host name is {0}", Dns.gethostname ());
Console.WriteLine ("Waiting for a client ...");

//4. Client IP
IPEndPoint Sender=NewIPEndPoint (Ipaddress.any,0);
EndPoint Remote=(EndPoint) sender;

//5. Receiving Client data
Byte[] Buffer=NewByte[1024];
Socket. ReceiveFrom (Buffer,Refremote);

Cp2pmessage msg= new cp2pmessage ();
msg = (cp2pmessage) tool.bytestostruct (buffer, MSG. GetType ());

Console.WriteLine (" received value: {0}", MSG.) Value);

Console.readkey ();
}
}
}

2. An important part of this is converting a struct to a byte array

UsingSystem;
UsingSystem.Collections.Generic;
UsingSystem.IO;
UsingSystem.Runtime.InteropServices;

NamespaceLin.p2p.Mo
{
PublicClassTool
{
PublicStaticByte[] Structtobytes (ObjectObj
{
IntSize=Marshal.SizeOf (obj);
Byte[] Bytes=NewByte[Size];
IntPtr structptr=Marshal.allochglobal (size);//Allocating the size of the structure to the memory space
Marshal.structuretoptr (obj, structptr,False);//Copy the structure to the allocated memory space
Marshal.Copy (structptr, Bytes,0, size);//Copy from memory space to byte array
Marshal.freehglobal (STRUCTPTR);//Free up memory space
Returnbytes
}

PublicStaticObjectBytestostruct (Byte[] bytes, type type)
{
IntSize=Marshal.SizeOf (type);
If(Size>bytes. Length)
ReturnNull;
IntPtr structptr=Marshal.allochglobal (size);//Allocating a structure-sized memory space
            marshal.copy (bytes,  0, structptr, size);        //
            < Span style= "color: #0000ff;" >object obj =  marshal.ptrtostructure (Structptr, type);
            marshal.freehglobal (STRUCTPTR);
             Return obj;
        }
    }
}

3. Last look at the client

//1. Create a nested section word
m_s=NewSockets (AddressFamily.InterNetwork, Sockettype.dgram, PROTOCOLTYPE.UDP);

//2. Fill in the server IP
IPAddress IP=Ipaddress.parse ("127.0.0.1");
IPEndPoint Ipe=NewIPEndPoint (IP,4321);


//Send this user information to the server
Cp2pmessage msg=NewCp2pmessage ();
Msg.nmessagetypes= (sbyte) Cmd.userlogin;
Msg. Value = ten;

var buffer = fun.structtobytes (msg);

M_s.sendto (buffer, buffer. Length, Socketflags.none, IPE);

Console.readkey ();

4. Haha, of course, the effect comes also ~ ~

C # Socket get started 4 UPD send fabric body (GO)

Related Article

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.