<span style="font-size:18px;">在dotnet平台Net.Sockets.TcpListener和Net.Sockets.TcpClient已经为我们封装了全部Socket关于tcp部分,操作也更为简单,面向数据流。使用TcpClient的GetStream方法获取数据流后能够方便的对数据流进行读写操作,就如同本地磁盘的文件读写一样,使得程序猿在设计程序时更为便捷简单。</span>

但假设你使用过这两个对象进行传输数据的时候,你会发现问题也随之而来——GetStream获取的数据流是一个永无止境的Stream,你无法获取它的详细长度。

来看一下微软MSDN关于这两个对象的例程:

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

你不得不去指定一个固定尺寸的缓冲区来接收数据,假设实际发送的数据超出了这个长度,你可能无法接收到所有完整的数据,而假设发送的数据少于缓冲区的大小,那么非常显然你的内存会比别人消耗的更快。更为严重的时。假设你要发送一副图片,图片容量可能依据内容的不同而各有千秋,容量也不止256Byte这么小,该怎样精确控制缓冲区呢?

事实上我们能够非常easy的解决问题,就像非常多文件格式所做的事情一样,我们能够在Stream的前几个字节写入实际有效数据的长度。然后依据这个长度来分配内存。再读取内容,我所做的client与server之间传递屏幕的源码例如以下:

'----------------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.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 Sub
End 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 '创建图片
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() '存入内存
Dim mem As New IO.MemoryStream
bmp.Save(mem, Drawing.Imaging.ImageFormat.Tiff) '文件长度
slen = mem.Length
slens = BitConverter.GetBytes(slen) '发送长度
For i = 0 To 7
tcpc.GetStream.WriteByte(slens(i))
Next
'发送内容
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 Sub
End Class

使用Net.Sockets.TcpListener和Net.Sockets.TcpClient进行图片传输时怎样精确控制接收缓存数组大小的更多相关文章

  1. C# Socket TcpClient 无法从传输连接中读取数据: 远程主机强迫关闭了一个现有的连接。。

    开始的代码: byte[] data = Encoding.UTF8.GetBytes(sInfo);                    tcpns.Write(data, 0,1024); 修改 ...

  2. TcpClient

    public class TcpClientSession { protected TcpClient Client { get; set; } /// <summary> /// 远程地 ...

  3. records.config文件参数解释

    # Process Records Config File # # <RECORD-TYPE> <NAME> <TYPE> <VALUE (till end ...

  4. TCP的发送系列 — 发送缓存的管理(一)

    主要内容:TCP发送缓存的初始化.动态调整.申请和释放. 内核版本:3.15.2 我的博客:http://blog.csdn.net/zhangskd 数据结构 TCP对发送缓存的管理是在两个层面上进 ...

  5. records.config中文详解

    转载:http://www.safecdn.cn/cdn/2018/12/records-config-zh/106.html records.config参数的一些备注 CONFIG proxy.c ...

  6. TCP 接收窗口自动调节

    https://technet.microsoft.com/zh-cn/magazine/2007.01.cableguy.aspx 欢迎来到 TechNet 杂志“网络专家”的第一部分.TechNe ...

  7. wp socket tcp链接

    using System; using System.Net; /// <summary> /// 客户端通过TCP/IP连接服务端的方法,包含连接,发送数据,接收数据功能 /// < ...

  8. Linux 内核参数说明

    转载自: https://www.cnblogs.com/tolimit/p/5065761.html 因个人能力有限,不能保证所有描述都正确,还请大家集思广益,有错误的地方欢迎大家留言指正,同时也欢 ...

  9. Nginx之核心结构体ngx_cycle_t

    1. ngx_listening_t 结构体 ngx_cycle_t 对象中有一个动态数组成员叫做 listening,它的每个数组元素都是 ngx_listening_t 结构体,而每个 ngx_l ...

随机推荐

  1. Cannot call sendError() after the response has been committed(filter问题)

    就是因为执行了filter的dofilter方法中 chain.doFilter(request,response)了 执行了两遍 if(){}else{chain.doFilter(request, ...

  2. 开源 SHOPNC B2B2C结算营运版 wap IM客服 API 手机app 短信通知

    源码我们这里简单的测试了下,具体的请自行下载测试.这套源码官方售价很高,在这里完全免费分享,无任何限制,安装也简单. 源码下载后请自行检测安全,在使用过程中发生的任何问题请自行处理,本站不承担任何责任 ...

  3. Android常用传感器用法一览(1)

    1.传感器入门自从苹果公司在2007年发布第一代iPhone以来,以前看似和手机挨不着边的传感器也逐渐成为手机硬件的重要组成部分.如果读者使用过iPhone.HTC Dream.HTC Magic.H ...

  4. 常用命令(过滤、管道、重定向、ping 命令、netstat 命令、ps命令)

    常用命令 过滤 过滤出 /etc/passwd 文件中包含 root 的记录 grep 'root' /etc/passwd 递归地过滤出 /var/log/ 目录中包含 linux 的记录 grep ...

  5. Cocos2d-x设置吞没单击属性来避免精灵重叠被点击后的事件续传

    代码如下: Size visibleSize = Director::getInstance()->getVisibleSize(); /* create two sprites which h ...

  6. Ubuntu 下安装adobe reader

    ctrl+alt+t打开终端 wget ftp://ftp.adobe.com/pub/adobe/reader/unix/9.x/9.5.5/enu/AdbeRdr9.5.5-1_i386linux ...

  7. Win8 Metro中文件读写删除与复制操作

    Win8Metro中,我们不能在向以前那样调用WIN32的API函数来进行文件操作,因此,下面就来介绍一下Win8 Metro中文件的读写操作. 1 Windows 8 Metro Style App ...

  8. android 蓝牙SPP协议通信

    准备 1.蓝牙串行端口基于SPP协议(Serial Port Profile),能在蓝牙设备之间创建串口进行数据传输 2.SPP的UUID:00001101-0000-1000-8000-00805F ...

  9. 算法笔记_084:蓝桥杯练习 11-1实现strcmp函数(Java)

    目录 1 问题描述 2 解决方案   1 问题描述 问题描述 自己实现一个比较字符串大小的函数,也即实现strcmp函数.函数:int myStrcmp(char *s1,char *s2) 按照AS ...

  10. 修改tcp数据内容

    http://blog.sina.com.cn/s/blog_6f0c85fb0100xi1x.html 2.6内核基于NetFilter处理框架修改TCP数据包实现访问控制 参考上面的钩子函数,结合 ...