I've made wrappers of the TcpClient/Listener
classes which include these functions to send/receive data:
Function sendBytes(ByVal stream As NetworkStream, ByVal data As Byte()) As Boolean
Function receiveBytes(ByVal stream As NetworkStream) As Byte()
They work well, but now I'm looking to send data other than just String
objects and file data.
So I'm hoping to then create these functions which can send/receive anything:
Function send(ByVal stream As NetworkStream, ByVal obj As Object) As Boolean
Return sendBytes(stream, serialize(obj))
End Function
Function receive(ByVal stream As NetworkStream) As Object
Return deserialize(receiveBytes(stream))
End Function
(From a bit of research, including this link, I gather that protocol buffers are the best way to go in terms of compactness and speed, so I think that's what I'll use for serialize()
and deserialize()
, although I may initially start with the BinaryFormatter
class)
Although this would be ideal, I have no idea if this would be a sensible way to carry this out. In addition to complicated objects I would have no other way of sending, I would also be passing simple objects such as Strings, Ints and even Byte() arrays which already have their own methods to convert into binary (or not even need it at all).
I have no idea — would the serializer do extra unnecessary work on those objects, especially the Byte() array which wouldn't need to be changed at all?
If so, then would it mean I should actually write the send/receive functions so that it considers cases for different types? Which means something like this:
Function send(ByVal stream As NetworkStream, ByVal obj As Object) As Boolean
Dim data As Byte()
Select Case obj.GetType
Case GetType(String)
data = Text.Encoding.ASCII.GetBytes(obj)
Case GetType(Int32)
data = BitConverter.ToInt32(obj)
Case GetType(Byte())
data = obj
Case ...
...
Case Else
data = serialize(obj)
End Select
Return sendBytes(stream, data)
End Function
and the equivalent for receive. (I would also have to add some sort of header describing the type of object being sent too so the receive function knows what to do with it, although I haven't included it in the above example code)
I've only listed some of the types which I thought might not need serialization as examples, but of course, there are more (eg. Boolean), hence the (...).