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)