使用套接字编程在.NET中传输Tcp / IP文件 [英] Tcp/IP file transfer in .NET using socket programming
问题描述
我正在尝试通过VB.NET应用程序中的TCP / IP传输文件,我有关于传输文件大小的问题,这里是代码:
服务器:
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
Imports System.ComponentModel
Class MainWindow
Dim 计时器作为 新秒表
昏暗 LocalAddr As IPAddress
Dim ServerSocket As TcpListener
Dim RequestCount As 整数
Dim ClientSocket As TcpClient
Dim BW 作为 新 BackgroundWorker 使用 {。WorkerSupportsCancellation = True }
Dim BWAccept As 新 BackgroundWorker 使用 {。WorkerSupportsCancellation = True }
Dim FileStreamer As 新 System.IO.FileStream( C:\ Users \m_shahgholi \Desktop \New folder \test.dcm,IO.FileMode.Create,IO.FileAccess.Write,IO.FileShare.ReadWrite)
私有 Sub DoWorker(发件人 As 对象,e As System.ComponentModel.DoWorkEventArgs)
while ( True )
尝试
RequestCount = RequestCount + 1
Dim networkStream As NetworkStream = ClientSocket.GetStream()
Dim bytesFrom(ClientSocket.ReceiveBufferSize) 作为 字节
networkStream.Read(bytesFrom, 0 , CInt (ClientSocket.ReceiveBufferSize))
' IO.File.WriteAllBytes(C:\ temp\1.dcm,bytesFrom)
我 .Dispatcher.Invoke( Sub ()
如果 ClientSocket.Available<> 0 然后
TextBoxClientBufferSize.Text = ClientSocket.Available.ToString
结束 如果
FileStreamer.Write(bytesFrom, 0 , CInt (ClientSocket.ReceiveBufferSize))
结束 Sub )
' Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
' dataFromClient = dataFromClient.Substring(0,dataFromClient.IndexOf($))
' msg(来自客户端的数据 - + dataFromClient)
Dim serverResponse 作为 字符串 = 服务器响应 + Convert.ToString(RequestCount)+ $
< span class =code-keyword> Dim sendBytes As Byte ()=编码。 UTF8.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0 ,sendBytes.Length)
networkStream.Flush()
msg (serverResponse)
' networkStream.Close()
Catch ex As Exception
< span class =code-keyword>退出
结束 尝试
结束
结束 Sub
私有 Sub CompleteWorker(发件人作为 Object ,e As System.ComponentModel.RunWorkerCompletedEventArgs)
ClientSocket.Close()
ServerSocket。停止()
msg( 退出)
StackPanelClient.Visibility = Windows.Visibility.Collapsed
Timer。 Stop ()
TextBoxClientBufferSize.Text = Timer.Elapsed.ToStrin g
FileStreamer.Close()
结束 Sub
Sub msg( ByVal mesg As 字符串)
mesg.Trim()
我 .Dispatcher.Invoke(
< span class =code-keyword> Sub ()
RichTextBoxRecivedText.AppendText(mesg + vbCrLf)
RichTextBoxRecivedText.ScrollToEnd()
结束 Sub )
结束 Sub
私有 Sub ButtonStart_Click(发送者 As System。 Object ,e As System.Windows。 RoutedEventArgs)句柄 ButtonStart.Click
TextBoxServerIP.Text = System.Net.Dns.GetHostByName(Dns.GetHostName())。AddressList( 0 )。ToString()
LocalAddr = IPAddress.Parse(TextBoxServerIP.Text)
ServerSocket = 新 TcpListener(LocalAddr, 8888 )
ServerSocket.Start()
msg( 服务器已启动)
WaitForClientProgressIndicator.Visibility = Windows.Visibility.Visible
LabelServerIP.Visibility = Windows.Visibility.Visible
TextBoxServerIP。 Visibility = Windows.Visibility.Visible
WaitForClientProgressIndicator.Start()
StackPanelServer.Background = Brushes.Red
AddHandler BWAccept.DoWork, AddressOf AcceptDoWorker
AddHandler BWAcce pt.RunWorkerCompleted, AddressOf AcceptCompleteWorker
BWAccept.RunWorkerAsync()
End Sub
私有 Sub AcceptDoWorker(发件人作为 对象,e As System.ComponentModel.DoWorkEventArgs)
ClientSocket = ServerSocket.AcceptTcpClient
ServerSocket.Server.ReceiveBufferSize = 8192 * 2
ClientSocket.ReceiveBufferSize = 8192 * 2
结束 Sub
私有 Sub AcceptCompleteWorker(发件人 As 对象,e As System.ComponentModel.RunWorkerCompletedEventArgs)
msg( 接受来自客户端的连接)
Me .Dispatcher.Invoke( Sub ()TextBoxClientBufferSize.Text = ClientSocket.ReceiveBufferSize)
RequestCount = 0
RichTextBoxRecivedText.Background = Brushes.Black
RichTextBoxRecivedText.Foreground = Brushes.WhiteSmoke
WaitForClientProgressIndicator.Visibility = Windows.Visibility.Collapsed
WaitForClientProgressIndicator。结束()
ButtonStart.Visibility = Windows.Visibility.Collapsed
ButtonStop.Visibility = Windows.Visibility.Visible
AddHandler BW.DoWork, AddressOf DoWorke r
AddHandler BW.RunWorkerCompleted, AddressOf CompleteWorker
Timer.Start()
BW.RunWorkerAsync()
TextBoxClientIP.Text = DirectCast (ClientSocket.Client.RemoteEndPoint,IPEndPoint).Address.ToString
StackPanelClient。 Visibility = Windows.Visibility.Visible
StackPanelServer.Background = Brushes.WhiteSmoke
End Sub
私有 Sub ButtonStop_Click(发件人作为系统。对象,e 作为 System.Windows.RoutedEventArgs)句柄 ButtonStop.Click
ClientSocket.Close()
ServerSocket。停止()
msg( 服务器已停止)
ButtonStart.Visibility = Windows.Visibility.Visible
ButtonStop.Visibility = Windows.Visibility.Collapsed
BW.CancelAsync()
BWAccept.CancelAsync()
StackPanelClient.Visibility = Windows.Visibility.Collapsed
StackPanelServer.Visibility = Windows.Visibility.Collapsed
结束 Sub
结束 Class
客户:
Imports System.Net.Sockets
Imports System.IO
Class MainWindow
Dim networkStream As NetworkStream
私人 Sub ButtonStart_Click(sender As System。 Object ,e As System.Windows.RoutedEventArgs)句柄 ButtonStart.Click
Dim tcpClnt As 新 System.Net.Sockets.TcpClient
Dim port As 整数 = 8888
尝试
tcpClnt.Connect(TextBoxServerIP.Text,port)
networkStream = tcpClnt。 GetStream()
Catch ex As 异常
MsgBox(ex.ToString() )
结束 尝试
E nd Sub
私有 Sub ButtonSend_Click(sender As System。 Object ,e As System.Windows.RoutedEventArgs)句柄 ButtonSend.Click
Dim fs 作为 FileStream
fs = 新 FileStream( D:\ Software \ NIC \ DCM \Series1 \10.129.1125.111.1246.1101.20150106081616.1.dcm,FileMode .Open)
Dim objReader As New BinaryReader(fs)
Dim send() As 字节 = objReader.ReadBytes(fs.Length)
networkStream.Write(send, 0 ,send.Length)
objReader.Close()
fs.Close()
结束 Sub
私有 Sub Window_Loaded(发件人作为系统。对象,e 作为 System.Windows.RoutedEventArgs)句柄 MyBase .Loaded
TextBoxServerIP.Text = 192.168.1.106
结束 Sub
结束 类
我尝试了什么:
该应用程序有效,但有一个错误。假设一个文件大小为1000字节,在此代码中缓冲区大小为16KB。传输的文件是16KB而不是1000字节,并且在文件末尾添加了一些0。我必须做些什么来纠正?
))
' msg(来自客户端的数据 - + dataFromClient)
Dim serverResponse As String = 服务器响应 + Convert.ToString(RequestCount)+
< blockquote>
Dim sendBytes As Byte ()= Encoding.UTF8.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0 ,sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
' networkStream.Close()
Catch ex 作为例外
退出
结束 尝试
结束 while
结束 Sub
私有 Sub CompleteWorker(发件人正如 对象,e As System.ComponentModel.RunWorkerCompletedEventArgs)
ClientSocket.Close()
ServerSocket。停止()
msg( 退出)
StackPanelClient.Visibility = Windows.Visibility.Collapsed
Timer。 Stop ()
TextBoxClientBufferSize.Text = Timer.Elapsed.ToString
FileStreamer.Close()
结束 Sub
Sub msg( ByVal mesg As String )
mesg.Trim()
Me .Dispatcher.Invoke(
Sub ()
RichTextBoxRecivedText.AppendText(mesg + vbCrLf)
RichTextBoxRecivedText.ScrollToEnd()
End Sub )
结束 Sub
私有 Sub ButtonSt art_Click(发件人作为系统。对象,e As System.Windows.RoutedEventArgs)句柄 ButtonStart.Click
TextBoxServerIP.Text = System.Net.Dns.GetHostByName(Dns.GetHostName())。AddressList ( 0 )。ToString()
LocalAddr = IPAddress.Parse(TextBoxServerIP.Text)
ServerSocket = 新 TcpListener(LocalAddr, 8888 )
ServerSocket.Start()
msg( 服务器已启动)
WaitForClientProgressIndicator.Visibility = Windows.Visibility.Visible
LabelServerIP.Visibility = Windows .Visibility.Visible
TextBoxServerIP.Visibility = Windows.Visibility.Visible
WaitForClientProgressIndicator.Start()
StackPanelServer.Background = Brushes.Red
AddHandler BWAccept.DoWork, AddressOf AcceptDoWorker
AddHandler BWAccept.RunWorkerCompleted, AddressOf AcceptCompleteWorker
BWAccept.RunWorkerAsync()
End Sub
私有 Sub AcceptDoWorker(发件人作为 对象,e 正如 System.ComponentModel.DoWorkEventArgs)
ClientSocket = ServerSocket.AcceptTcpClient
ServerSocket.Server.ReceiveBufferSize = 8192 * 2
ClientSocket.ReceiveBufferSize = 8192 * 2
结束
私有 Sub AcceptCompleteWorker(sender As Object ,e As System.ComponentModel.RunWorkerCompletedEventArgs)
msg( 接受来自客户端的连接)
Me .Dispatcher.Invoke( Sub ()TextBoxClientBufferSize.Text = ClientSocket.ReceiveBufferSize)
RequestCount = 0
RichTextBoxRecivedText.Background = Brushes.Black
RichTextBoxRecivedText.Foreground = Brushes.WhiteSmoke
WaitForClientProgressIndicator.Visibility = Windows .Visibility.Collapsed
WaitForClientProgressIndicator。 End ()
ButtonStart.Visibility = Windows.Visibility.Co llapsed
ButtonStop.Visibility = Windows.Visibility.Visible
AddHandler BW.DoWork, AddressOf DoWorker
AddHandler BW.RunWorkerCompleted, AddressOf CompleteWorker
Timer.Start( )
BW.RunWorkerAsync()
TextBoxClientIP.Text = DirectCast (ClientSocket.Client.RemoteEndPoint,IPEndPoint).Address.ToString
StackPanelClient.Visibility = Windows.Visibility.Visible
StackPanelServer.Background = Brushes.WhiteSmoke
End Sub
私有 Sub ButtonStop_Click(发件人 As System。 Object ,e As System.Windows.RoutedEventArgs) 句柄 ButtonStop.Click
ClientSocket.Close()
ServerSocket。停止()
msg( 服务器已停止)
ButtonStart.Visibility = Windows.Visibility.Visible
ButtonStop.Visibility = Windows.Visibility.Collapsed
BW.CancelAsync()
BWAccept.CancelAsync()
StackPanelClient.Visibility = Windows.Visibility.Collapsed
StackPanelServer。可见性= Windows.Visibility.Collapsed
结束 Sub
< span class =code-keyword>结束 类
客户:
Imports System.Net.Sockets
Imports System.IO
班级 Ma inWindow
Dim networkStream As NetworkStream
私有 Sub ButtonStart_Click(发件人 As 系统。 Object ,e As System.Windows.RoutedEventArgs) Handles ButtonStart。单击
Dim tcpClnt 作为 新 System.Net.Sockets.TcpClient
Dim port As Integer = 8888
尝试
tcpClnt.Connect (TextBoxServerIP.Text,port)
networkStream = tcpClnt.GetStream()
Catch ex As 异常
MsgBox(ex.ToString())
结束 尝试
结束 Sub
< span class =code-keyword>私有 Sub ButtonSend_Click(发件人作为系统。< span class =code-keyword> Object ,e As System.Windows.RoutedEventArgs) Handles ButtonSend.Click
Dim fs As FileStream
fs = 新 FileStream( D:\Software\NIC \ DCM \Series1 \10.129.1125.111.1246.1101.20150106081616.1.dcm,FileMode.Open)
Dim objReader 作为 新 BinaryReader(fs)
Dim send()作为 字节 = objReader.ReadBytes(fs.Length)
networkStream.Write(send, 0 ,send.Length)
objReader.Close()
fs.Close()
结束 < span class =code-keyword> Sub
私有 Sub Window_Loaded(sender As System。 Object ,e As System.Windows.RoutedEventArgs)句柄 MyBase .Loaded
TextBoxServerIP.Text = 192.168.1.106
结束 Sub
结束 类
我尝试过:
该应用程序可以正常运行,但有错误。假设一个文件大小为1000字节,在此代码中缓冲区大小为16KB。传输的文件是16KB而不是1000字节,并且在文件末尾添加了一些0。我必须做些什么来纠正?
你在这里写文件
ClientSocket.ReceiveBufferSize
字节:
FileStreamer.Write(bytesFrom, 0 , CInt (ClientSocket.ReceiveBufferSize ))
即使您收到的字节数较少。
您必须使用实际收到的字节数,而不是 NetworkStream.Read()
:
Dim numberOfBytesRead As < span class =code-keyword> Integer = 0
numberOfBytesRead = networkStream.Read(bytesFrom, 0 ,bytesFrom.Length)
' ...
FileStreamer.Write(bytesFrom, 0 ,numberOfBytesRead)
I am trying to transfer files through TCP/IP in a VB.NET application and I have problem about the size of transferred file here is the codes:
Server:
Imports System.Net.Sockets
Imports System.Text
Imports System.Net
Imports System.ComponentModel
Class MainWindow
Dim Timer As New Stopwatch
Dim LocalAddr As IPAddress
Dim ServerSocket As TcpListener
Dim RequestCount As Integer
Dim ClientSocket As TcpClient
Dim BW As New BackgroundWorker With {.WorkerSupportsCancellation = True}
Dim BWAccept As New BackgroundWorker With {.WorkerSupportsCancellation = True}
Dim FileStreamer As New System.IO.FileStream("C:\Users\m_shahgholi\Desktop\New folder\test.dcm", IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.ReadWrite)
Private Sub DoWorker(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
While (True)
Try
RequestCount = RequestCount + 1
Dim networkStream As NetworkStream = ClientSocket.GetStream()
Dim bytesFrom(ClientSocket.ReceiveBufferSize) As Byte
networkStream.Read(bytesFrom, 0, CInt(ClientSocket.ReceiveBufferSize))
'IO.File.WriteAllBytes("C:\temp\1.dcm", bytesFrom)
Me.Dispatcher.Invoke(Sub()
If ClientSocket.Available <> 0 Then
TextBoxClientBufferSize.Text = ClientSocket.Available.ToString
End If
FileStreamer.Write(bytesFrom, 0, CInt(ClientSocket.ReceiveBufferSize))
End Sub)
'Dim dataFromClient As String = System.Text.Encoding.ASCII.GetString(bytesFrom)
'dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
'msg("Data from client - " + dataFromClient)
Dim serverResponse As String = "Server response " + Convert.ToString(RequestCount) + "$"
Dim sendBytes As Byte() = Encoding.UTF8.GetBytes(serverResponse)
networkStream.Write(sendBytes, 0, sendBytes.Length)
networkStream.Flush()
msg(serverResponse)
'networkStream.Close()
Catch ex As Exception
Exit While
End Try
End While
End Sub
Private Sub CompleteWorker(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
ClientSocket.Close()
ServerSocket.Stop()
msg("exit")
StackPanelClient.Visibility = Windows.Visibility.Collapsed
Timer.Stop()
TextBoxClientBufferSize.Text = Timer.Elapsed.ToString
FileStreamer.Close()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Me.Dispatcher.Invoke(
Sub()
RichTextBoxRecivedText.AppendText(mesg + vbCrLf)
RichTextBoxRecivedText.ScrollToEnd()
End Sub)
End Sub
Private Sub ButtonStart_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStart.Click
TextBoxServerIP.Text = System.Net.Dns.GetHostByName(Dns.GetHostName()).AddressList(0).ToString()
LocalAddr = IPAddress.Parse(TextBoxServerIP.Text)
ServerSocket = New TcpListener(LocalAddr, 8888)
ServerSocket.Start()
msg("Server Started")
WaitForClientProgressIndicator.Visibility = Windows.Visibility.Visible
LabelServerIP.Visibility = Windows.Visibility.Visible
TextBoxServerIP.Visibility = Windows.Visibility.Visible
WaitForClientProgressIndicator.Start()
StackPanelServer.Background = Brushes.Red
AddHandler BWAccept.DoWork, AddressOf AcceptDoWorker
AddHandler BWAccept.RunWorkerCompleted, AddressOf AcceptCompleteWorker
BWAccept.RunWorkerAsync()
End Sub
Private Sub AcceptDoWorker(sender As Object, e As System.ComponentModel.DoWorkEventArgs)
ClientSocket = ServerSocket.AcceptTcpClient
ServerSocket.Server.ReceiveBufferSize = 8192 * 2
ClientSocket.ReceiveBufferSize = 8192 * 2
End Sub
Private Sub AcceptCompleteWorker(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs)
msg("Accept connection from client")
Me.Dispatcher.Invoke(Sub() TextBoxClientBufferSize.Text = ClientSocket.ReceiveBufferSize)
RequestCount = 0
RichTextBoxRecivedText.Background = Brushes.Black
RichTextBoxRecivedText.Foreground = Brushes.WhiteSmoke
WaitForClientProgressIndicator.Visibility = Windows.Visibility.Collapsed
WaitForClientProgressIndicator.End()
ButtonStart.Visibility = Windows.Visibility.Collapsed
ButtonStop.Visibility = Windows.Visibility.Visible
AddHandler BW.DoWork, AddressOf DoWorker
AddHandler BW.RunWorkerCompleted, AddressOf CompleteWorker
Timer.Start()
BW.RunWorkerAsync()
TextBoxClientIP.Text = DirectCast(ClientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString
StackPanelClient.Visibility = Windows.Visibility.Visible
StackPanelServer.Background = Brushes.WhiteSmoke
End Sub
Private Sub ButtonStop_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStop.Click
ClientSocket.Close()
ServerSocket.Stop()
msg("Server Stopped")
ButtonStart.Visibility = Windows.Visibility.Visible
ButtonStop.Visibility = Windows.Visibility.Collapsed
BW.CancelAsync()
BWAccept.CancelAsync()
StackPanelClient.Visibility = Windows.Visibility.Collapsed
StackPanelServer.Visibility = Windows.Visibility.Collapsed
End Sub
End Class
Client:
Imports System.Net.Sockets
Imports System.IO
Class MainWindow
Dim networkStream As NetworkStream
Private Sub ButtonStart_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStart.Click
Dim tcpClnt As New System.Net.Sockets.TcpClient
Dim port As Integer = 8888
Try
tcpClnt.Connect(TextBoxServerIP.Text, port)
networkStream = tcpClnt.GetStream()
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
Private Sub ButtonSend_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonSend.Click
Dim fs As FileStream
fs = New FileStream("D:\Software\NIC\DCM\Series1\10.129.1125.111.1246.1101.20150106081616.1.dcm", FileMode.Open)
Dim objReader As New BinaryReader(fs)
Dim send() As Byte = objReader.ReadBytes(fs.Length)
networkStream.Write(send, 0, send.Length)
objReader.Close()
fs.Close()
End Sub
Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
TextBoxServerIP.Text = "192.168.1.106"
End Sub
End Class
What I have tried:
The application works, but with an error. Suppose a file with the size of 1000 byte, in this code the buffer size is 16KB. The transferred file is 16KB not 1000 byte and some 0 is added to the end of file. What I must do for correction?
")) 'msg("Data from client - " + dataFromClient) Dim serverResponse As String = "Server response " + Convert.ToString(RequestCount) + "
" Dim sendBytes As Byte() = Encoding.UTF8.GetBytes(serverResponse) networkStream.Write(sendBytes, 0, sendBytes.Length) networkStream.Flush() msg(serverResponse) 'networkStream.Close() Catch ex As Exception Exit While End Try End While End Sub Private Sub CompleteWorker(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) ClientSocket.Close() ServerSocket.Stop() msg("exit") StackPanelClient.Visibility = Windows.Visibility.Collapsed Timer.Stop() TextBoxClientBufferSize.Text = Timer.Elapsed.ToString FileStreamer.Close() End Sub Sub msg(ByVal mesg As String) mesg.Trim() Me.Dispatcher.Invoke( Sub() RichTextBoxRecivedText.AppendText(mesg + vbCrLf) RichTextBoxRecivedText.ScrollToEnd() End Sub) End Sub Private Sub ButtonStart_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStart.Click TextBoxServerIP.Text = System.Net.Dns.GetHostByName(Dns.GetHostName()).AddressList(0).ToString() LocalAddr = IPAddress.Parse(TextBoxServerIP.Text) ServerSocket = New TcpListener(LocalAddr, 8888) ServerSocket.Start() msg("Server Started") WaitForClientProgressIndicator.Visibility = Windows.Visibility.Visible LabelServerIP.Visibility = Windows.Visibility.Visible TextBoxServerIP.Visibility = Windows.Visibility.Visible WaitForClientProgressIndicator.Start() StackPanelServer.Background = Brushes.Red AddHandler BWAccept.DoWork, AddressOf AcceptDoWorker AddHandler BWAccept.RunWorkerCompleted, AddressOf AcceptCompleteWorker BWAccept.RunWorkerAsync() End Sub Private Sub AcceptDoWorker(sender As Object, e As System.ComponentModel.DoWorkEventArgs) ClientSocket = ServerSocket.AcceptTcpClient ServerSocket.Server.ReceiveBufferSize = 8192 * 2 ClientSocket.ReceiveBufferSize = 8192 * 2 End Sub Private Sub AcceptCompleteWorker(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) msg("Accept connection from client") Me.Dispatcher.Invoke(Sub() TextBoxClientBufferSize.Text = ClientSocket.ReceiveBufferSize) RequestCount = 0 RichTextBoxRecivedText.Background = Brushes.Black RichTextBoxRecivedText.Foreground = Brushes.WhiteSmoke WaitForClientProgressIndicator.Visibility = Windows.Visibility.Collapsed WaitForClientProgressIndicator.End() ButtonStart.Visibility = Windows.Visibility.Collapsed ButtonStop.Visibility = Windows.Visibility.Visible AddHandler BW.DoWork, AddressOf DoWorker AddHandler BW.RunWorkerCompleted, AddressOf CompleteWorker Timer.Start() BW.RunWorkerAsync() TextBoxClientIP.Text = DirectCast(ClientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString StackPanelClient.Visibility = Windows.Visibility.Visible StackPanelServer.Background = Brushes.WhiteSmoke End Sub Private Sub ButtonStop_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStop.Click ClientSocket.Close() ServerSocket.Stop() msg("Server Stopped") ButtonStart.Visibility = Windows.Visibility.Visible ButtonStop.Visibility = Windows.Visibility.Collapsed BW.CancelAsync() BWAccept.CancelAsync() StackPanelClient.Visibility = Windows.Visibility.Collapsed StackPanelServer.Visibility = Windows.Visibility.Collapsed End Sub End Class
Client:
Imports System.Net.Sockets Imports System.IO Class MainWindow Dim networkStream As NetworkStream Private Sub ButtonStart_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonStart.Click Dim tcpClnt As New System.Net.Sockets.TcpClient Dim port As Integer = 8888 Try tcpClnt.Connect(TextBoxServerIP.Text, port) networkStream = tcpClnt.GetStream() Catch ex As Exception MsgBox(ex.ToString()) End Try End Sub Private Sub ButtonSend_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ButtonSend.Click Dim fs As FileStream fs = New FileStream("D:\Software\NIC\DCM\Series1\10.129.1125.111.1246.1101.20150106081616.1.dcm", FileMode.Open) Dim objReader As New BinaryReader(fs) Dim send() As Byte = objReader.ReadBytes(fs.Length) networkStream.Write(send, 0, send.Length) objReader.Close() fs.Close() End Sub Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded TextBoxServerIP.Text = "192.168.1.106" End Sub End Class
What I have tried:
The application works, but with an error. Suppose a file with the size of 1000 byte, in this code the buffer size is 16KB. The transferred file is 16KB not 1000 byte and some 0 is added to the end of file. What I must do for correction?
You are writingClientSocket.ReceiveBufferSize
bytes to the file here:
FileStreamer.Write(bytesFrom, 0, CInt(ClientSocket.ReceiveBufferSize))
even when you have received less bytes.
You must use the number of bytes that has been actually received instead which are returned byNetworkStream.Read()
:
Dim numberOfBytesRead As Integer = 0 numberOfBytesRead = networkStream.Read(bytesFrom, 0, bytesFrom.Length) '... FileStreamer.Write(bytesFrom, 0, numberOfBytesRead)
这篇关于使用套接字编程在.NET中传输Tcp / IP文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!