Reputation: 131
The problem is whenever I send files the file will be sent but it is always empty (0 bytes) and I've got no clue what's causing this.
Here is the code for the sender:
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
And here is the code for the receiver:
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
Upvotes: 1
Views: 64