1. 程式人生 > >使用Socket對序列化數據進行傳輸(基於C#)

使用Socket對序列化數據進行傳輸(基於C#)

ddr 傳輸 void receive sockets read 客戶端代碼 ets BE

客戶端代碼

[Serializable] // 表示該類可以被序列化
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(); //創建序列化對象
client.Connect(point); //連接服務器

MemoryStream ms = new MemoryStream(); //創建內存流對象
bf.Serialize(ms, p); //將p序列化到內存流中

client.Send(ms.GetBuffer(),(int)ms.Length,SocketFlags.None);// 發送,長度為內存流中數據的長度


}
}

服務器代碼

[Serializable] // 表示該類可以被序列化
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(); //等待客戶端連接

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();

}


}

使用Socket對序列化數據進行傳輸(基於C#)