-
Notifications
You must be signed in to change notification settings - Fork 0
serialization
#Data Serialization
Data serialization, for our purposes, simply refers to taking a block of data and transmitting it one byte at a time over some interface. This tutorial will give an example using sockets and the C programming language, but the concepts are the same for Java.
One common application for this technique is in sending a mix of quantitative and qualitative information all at once in a big string of characters. The following C example transmits a number of fields over a TCP socket. This is done with the expectation that the receiving end will parse the transmitted string and that there is some previously agreed upon format for the data string.
char buf[] = "Time: 15:05CST,\n
Temperature: 50F,\n
Unit ID: 15105,\n
Status: OK";
write(socketfd, buf, sizeof(buf));
In this C example, a .png image is read into a program as its individual bytes and then transmitted in order over a TCP socket.
FILE* fp = fopen("image.png","rb"); //open image.png for binary reading
char buf[32768]; //allocate 32K buffer for serializing image data (watch out for RAM usage)
int bytes_read = 0;
while(!feof(fp)) //keep going until we reach the end of the file
{
bytes_read = fread(buf, sizeof(char), sizeof(buf), fp); //read as many bytes as possible from the image
write(socketfd, buf, bytes_read); //serially write as many bytes as we have in the buffer to the socket
bzero(buf, sizeof(buf));
}
These example programs transmit a serialized screenshot image from the server to the client over a TCP socket.
Server
Client