问题是每当我发送文件时文件都会被发送,但它总是空的(0字节),我不知道是什么造成了这个。
以下是发件人的代码:
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class Form2
Dim filePath As String
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Button2.Enabled = False
TextBox1.Enabled = False
filePath = TextBox2.Text
Dim sendThread As New Thread(AddressOf SendSub)
sendThread.IsBackground = True
sendThread.Start()
End Sub
Private Sub SendSub()
Dim client As New TcpClient
client.Connect(TextBox1.Text, 2222)
Try
Dim nstm As Stream = client.GetStream
Dim fstm As Stream = New FileStream(filePath, FileMode.Open, FileAccess.Read)
Dim buffer(1024 - 1) As Byte
Do While True
Dim bytesRead As Integer = fstm.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then Exit Do
nstm.Write(buffer, 0, bytesRead)
nstm.Flush()
Loop
client.Close()
nstm.Close()
fstm.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
Dim diag As New OpenFileDialog
diag.InitialDirectory = "C:\"
diag.Filter = "All Files (*.*)|*.*|All Files (*.*)|*.*"
diag.FilterIndex = 2
diag.RestoreDirectory = True
If diag.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox2.Text = diag.FileName
End If
End Sub
End Class
以下是接收器的代码:
Imports System.IO
Imports System.Net
Imports System.Net.Sockets
Public Class Form1
Dim filepath As String
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Enabled = False
TextBox1.Enabled = False
filepath = TextBox1.Text
Dim listenerThread As New Threading.Thread(AddressOf ListeningSub)
listenerThread.IsBackground = True
listenerThread.Start()
End Sub
Private Sub ListeningSub()
Dim server As New TcpListener(IPAddress.Any, 2222)
server.Start()
Try
While True
Dim c As TcpClient = server.AcceptTcpClient
Dim s As NetworkStream = c.GetStream
FileOpen(1, filepath, OpenMode.Binary)
Dim buffer(1024 - 1) As Byte
Do While True
Dim bytesRead As Integer = s.Read(buffer, 0, buffer.Length)
If bytesRead = 0 Then Exit Do
Loop
FileClose(1)
s.Close()
c.Close()
End While
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim diag As New OpenFileDialog
diag.InitialDirectory = "C:\"
diag.Filter = "All Files (*.*)|*.*|All Files (*.*)|*.*"
diag.FilterIndex = 2
diag.RestoreDirectory = True
If diag.ShowDialog = Windows.Forms.DialogResult.OK Then
TextBox1.Text = diag.FileName
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Form2.Show()
End Sub
End Class
答案 0 :(得分:2)
您根本不会写入目标文件。