How to precisely control the size of the received cache array when using Net. Sockets. TcpListener and Net. Sockets. TcpClient for Image Transmission? tcplistener

Source: Internet
Author: User
Tags getstream

How to precisely control the size of the received cache array when using Net. Sockets. TcpListener and Net. Sockets. TcpClient for Image Transmission? tcplistener

<Span style = "font-size: 18px;"> Net. sockets. tcpListener and Net. sockets. tcpClient has encapsulated all the Socket information about tcp for us. The operation is simpler and data-oriented. Using the GetStream method of TcpClient to obtain the data stream, you can easily read and write the data stream, just like reading and writing files on the local disk, making it easier for programmers to design programs. </Span>

However, if you have used these two objects for data transmission, you will find that the problem also arises-the Data Stream Obtained by GetStream is a never-ending Stream, and you cannot get its specific length.

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

Shared Sub Connect(server As [String], message As [String])   Try      ' Create a TcpClient.      ' Note, for this client to work you need to have a TcpServer       ' connected to the same address as specified by the server, port      ' combination.      Dim port As Int32 = 13000      Dim client As New TcpClient(server, port)      ' Translate the passed message into ASCII and store it as a Byte array.      Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)      ' Get a client stream for reading and writing.      '  Stream stream = client.GetStream();      Dim stream As NetworkStream = 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.      Dim responseData As [String] = [String].Empty      ' Read the first batch of the TcpServer response bytes.      Dim bytes As Int32 = 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()   Catch e As ArgumentNullException      Console.WriteLine("ArgumentNullException: {0}", e)   Catch e As SocketException      Console.WriteLine("SocketException: {0}", e)   End Try   Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")   Console.Read()End Sub 'Connect
You have to specify a fixed-size buffer to receive data. If the actually sent data exceeds this length, you may not be able to receive all the complete data, if the data sent is smaller than the buffer size, your memory will obviously consume faster than others. In more serious cases, if you want to send an image, the image size may vary depending on the content, and the size is smaller than bytes. How can we precisely control the buffer?

In fact, we can easily solve this problem. Just like what many file formats do, we can write the actual length of valid data in the first few bytes of Stream, then allocate the memory according to the length and read the content. The source code of the screen transmitted 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("", 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.Text = 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) Handles MyBase.Load    End SubEnd Class


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

Public Class Form1 Private Sub backgroundworkerincludowork (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 image 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 () 'is stored in the memory Dim mem As New IO. memoryStream bmp. save (mem, Drawing. imaging. imageFormat. tiff) 'file length slen = mem. length slens = BitConverter. getBytes (slen) 'sending length For I = 0 To 7 tcpc. getStream. writeByte (slens (I) Next 'sends tcpc content. 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

For emergency assistance, the system prompts that you cannot connect to the remote server SystemNetSocketsSocketException during data transmission. may be useful to you

Related Article

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: 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.