Using the socket to transfer serialized data (C # based)

Source: Internet
Author: User

Client code

[Serializable]//indicates that the class can be serialized
Class Person
{
public string name;

public void HI ()
{
Debug.Log (name);
}
}

public class Newsocketclient:monobehaviour {

void Start () {

Person p = new person ();
P.name = "Lz";
Socket client = new socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);

IPEndPoint point = new IPEndPoint (Ipaddress.parse ("10.6.0.78"), 5684);
BinaryFormatter bf = new BinaryFormatter (); Creating a serialized object
Client. Connect (point); Connecting to a server

MemoryStream ms = new MemoryStream (); Create a memory Stream object
Bf. Serialize (MS, p); Serialize p to the memory stream

Client. Send (Ms. GetBuffer (), (int) Ms. Length,socketflags.none);//Send, length is the length of the data in the memory stream


}
}

Server code

[Serializable]//indicates that the class can be serialized
Class Person
{
public string name;

public void HI ()
{
Debug.Log (name);
}
}

public class Newsocketserver:monobehaviour
{

Socket Server_socket;

void Start ()
{
Server_socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp);

IPEndPoint point = new IPEndPoint (Ipaddress.any, 5684);

Server_socket.bind (point);

Server_socket.listen (10);

Thread acthread = new Thread (acthread);

Acthread.start ();
}


void Acthread ()
{

Socket clientsocket = server_socket.accept (); Waiting for client connections

byte[] buffer = new byte[1024 * 1024];

int len = clientsocket.receive (buffer);

MemoryStream memory = new MemoryStream ();

BinaryFormatter bf = new BinaryFormatter ();

Memory. Write (buffer, 0, Len);
Memory. Flush ();
Memory. Position = 0;

Person p = bf. Deserialize (memory) as person;
P.hi ();

}


}

Using the socket to transfer serialized data (C # based)

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.