在c#中使用异步套接字发送对象 [英] sending object using asynchronous socket in c#
问题描述
我正在开发基于套接字的客户端/服务器应用程序。我想将我定义的类的对象发送到服务器。这是My Defined类
Hi,
I am working on a socket based client/server application. I want to send a object of my defined Class to server. Here is My Defined class
public class ClientData
{
int clientId;
string clientName;
string message;
public ClientData(int _id, string _name, string _message)
{
this.clientId = _id;
this.clientName = _name;
tbis.message = _message
}
}
我使用异步套接字所以我是使用 Socket.BeginSend
函数。但我的问题是BeginSend只接受字节数组作为数据缓冲区,我不知道如何将ClientData对象转换为字节数组,而不是将其转换回服务器端的ClientData对象。
提前感谢您的时间。
I am using asyncronous sockets so i am using Socket.BeginSend
function. But my problem is that BeginSend only takes array of bytes as data buffer, i dont know how to convert ClientData object to array of bytes and than convert it back to ClientData object on server side.
thanks in advance for you time.
推荐答案
使用序列化是一种好方法,但是它增加了很多你可能不需要的开销。我会添加两个函数,例如:
Using serialization is a good way, however it adds a lot of overhead that you probably don't need. I would add two functions, like:
public byte[] ToBytes()
{
using (MemoryStream ms = new MemoryStream)
{
BinaryWriter bw = new BinaryWriter(ms);
bw.Write(clientId);
bw.Write(clientName);
bw.Write(message);
return ms.ToArray()
}
}
public static ClientData FromBytes(byte[] buffer)
{
ClientData retVal = new ClientData();
using (MemoryStream ms = new MemoryStream(buffer))
{
BinaryReader br = new BinaryReader(ms);
retVal.clientId = br.ReadInt32()
retVal.clientName = br.ReadString();
retVal.message = br.ReadString();
}
return retVal;
}
只需确保将字符串初始化为 string.empty
而不是null,以便它可以读取并正确写入它们。
Just make sure to initialize your strings to string.empty
instead of null so that it can read them and write them correctly.
这篇关于在c#中使用异步套接字发送对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!