How to precisely control the size of the receive cache array when using Net.Sockets.TcpListener and Net.Sockets.TcpClient for picture transfer

Source: Internet
Author: User
Tags getstream

<span style= "FONT-SIZE:18PX;" > in the Dotnet platform Net.Sockets.TcpListener and Net.Sockets.TcpClient have encapsulated all sockets for us on the TCP part, the operation is also simpler, oriented to data flow. Using the GetStream method of TcpClient, the data stream can be easily read and written, just as the local disk's file reads and writes, making the program ape easier and easier to design the program. </span>

But assuming you've used these two objects to transfer data, you'll see that the problem comes with it.--getstream The resulting stream is a never-ending stream, and you cannot get the detailed length of it.

Take a look at Microsoft MSDN's routines for these two objects:

Shared SubConnect (server as[String], message as[String])Try      ' Create a TcpClient.      ' Note, for this client to work with need to has a tcpserver      ' connected to the same address as specified by the server, Port      ' combination.      DimPort asInt32 = 13000DimClient as NewTcpClient (server, port)' Translate the passed message into ASCII and store it as a Byte array.      DimData as[Byte] () = System.Text.Encoding.ASCII.GetBytes (message)' Get a client stream for reading and writing.      ' Stream stream = client. GetStream ();      DimStream asNetworkStream = client. GetStream ()' Send the message to the connected TCPServer.Stream. Write (data, 0, data. Length) Console.WriteLine ("Sent: {0}", message)' Receive the tcpserver.response.      ' Buffer to store ' the response bytes.data =New[Byte] (256) {}' String to store ' The response ASCII representation.      DimResponseData as[String] = [String]. Empty' Read The first batch of the TCPServer response bytes.      Dimbytes asInt32 = stream. Read (data, 0, data. Length) ResponseData = System.Text.Encoding.ASCII.GetString (data, 0, bytes) Console.WriteLine ("Received: {0}", ResponseData)' Close everything.Stream. Close () client. Close ()CatchE asArgumentNullException Console.WriteLine ("ArgumentNullException: {0}"ECatchE asSocketException Console.WriteLine ("SocketException: {0}"EEnd TryConsole.WriteLine (ControlChars.Cr +"Press Enter to continue ...") Console.read ()End Sub ' Connect
You have to specify a fixed-size buffer to receive the data, assuming that the actual data sent exceeds that length, you may not be able to receive all the complete data, and assuming that the data sent is less than the buffer size, it is obvious that your memory will consume more quickly than others. More serious when. Suppose you want to send a picture, the image capacity may vary depending on the content, the capacity is more than 256Byte so small, how to precisely control the buffer?


In fact we are able to solve the problem very easily, just as many file formats do, we can write the length of the actual valid data in the first few bytes of the stream. The memory is then allocated according to this length. To read the content again, the source code that I have done to pass the screen between the client and the server is as follows:


'----------------Client----------------

<pre name= "code" class= "VB" >public class Form1 Private Sub timer1_tick (ByVal sender as System.Object, ByVal e As            System.EventArgs) Handles Timer1.tick Dim tcpc As New Net.Sockets.TcpClient Dim Slens (7) as Byte Try Tcpc. Connect ("127.0.0.1", 2099) If TCPC. Connected then for i = 0 to 7 slens (i) = Tcpc. Getstream.readbyte Next Dim buf (Bitconverter.touint64 (slens, 0)) as Byte me.t ext = buf. Length TCPC. Getstream.read (buf, 0, buf. Length) Dim mem as New IO. MemoryStream (BUF) Dim bmp as New Bitmap (mem) Me.PictureBox1.Image = BMP tcpc. Close () End If Catch ex as Exception Finally TCPC. Close () End Try End Sub Private Sub Form1_Load (ByVal sender as System.Object, ByVal e as System.EventArgs) Ha Ndles mybase.load End subend Class



'------------Server----------------

Public Class Form1 Private Sub backgroundworker1_dowork (ByVal sender as System.Object, ByVal e as System.ComponentModel . DoWorkEventArgs) Handles backgroundworker1.dowork Dim TCPs as New Net.Sockets.TcpListener (2099) TCPs. Start () While True Dim slen As UInt64 Dim slens (7) as Byte Dim tcpc As Net.sockets . TcpClient TCPC = TCPs. AcceptTcpClient ' Create picture Dim bmp as New Bitmap (Screen.PrimaryScreen.Bounds.Width, Screen.primaryscreen. bounds.height) BMP. Setresolution (1, 1) Dim gph as Graphics = Graphics.fromimage (BMP) Gph. CopyFromScreen (new point (0, 0), new Point (0, 0), BMP. Size) gph. Flush () ' into memory Dim mem as New IO. MemoryStream bmp. Save (Mem, Drawing.Imaging.ImageFormat.Tiff) ' file length Slen = Mem. Length Slens = bitconverter.getbytes (slen) ' Send lengths for i = 0 to 7 tcpc. GetstrEam. WriteByte (Slens (i)) Next ' send content tcpc. Getstream.write (Mem. ToArray, 0, Mem. Length) Tcpc. Close () End While end Sub Private Sub Form1_Load (ByVal sender as System.Object, ByVal e as System.EventArgs) Handles mybase.load Me.BackgroundWorker1.RunWorkerAsync () End subend Class



How to precisely control the size of the receive cache array when using Net.Sockets.TcpListener and Net.Sockets.TcpClient for picture transfer

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.