How to Send a file with TCP? - vb.net

I have been searching, and I cannot find any good examples of how to send a file with TCP. This is what I have tried so far:
Private Sub SendFile(FileName As String, Server As String, Port As Integer)
Dim TcpClient As New System.Net.Sockets.TcpClient(Server, Port)
Dim NetworkStream As System.Net.Sockets.NetworkStream = TcpClient.GetStream()
Dim Data() As Byte = System.Text.Encoding.ASCII.GetBytes(New System.IO.StreamReader(FileName).ReadToEnd())
NetworkStream.Write(Data, 0, Data.Length)
NetworkStream.Close()
End Sub
Thanks for any help.

I think this will work. This is the code for the client:
Private Sub SendFile(FileName As String, Server As String, Port As Integer)
Dim TcpClient As New System.Net.Sockets.TcpClient(Server, Port)
Dim NetworkStream As System.Net.Sockets.NetworkStream = TcpClient.GetStream()
Dim FileStream As System.IO.Stream = System.IO.File.OpenRead(FileName)
Dim FileBuffer(FileStream.Length) As Byte
FileStream.Read(FileBuffer, 0, FileStream.Length)
NetworkStream.Write(FileBuffer, 0, FileStream.Length)
NetworkStream.Close()
FileStream.Close()
End Sub
And this is the code for the server:
Private Sub ReceiveFile(FileName As String, Port As Integer)
Dim WorkerThread As New System.Threading.Thread(Sub()
Dim TcpListener As New System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, Port) : TcpListener.Start()
Dim HandlerSocket As System.Net.Sockets.Socket = TcpListener.AcceptSocket()
If HandlerSocket.Connected = True Then
Dim NetworkStream As New System.Net.Sockets.NetworkStream(HandlerSocket)
Dim BlockSize As Integer = 1024
Dim DataRead As Integer
Dim DataByte(BlockSize) As Byte
Dim FileStream As System.IO.Stream = System.IO.File.OpenWrite(FileName)
Do
DataRead = NetworkStream.Read(DataByte, 0, BlockSize)
FileStream.Write(DataByte, 0, DataByte.Length)
If DataRead = 0 Then
Exit Do
End If
Loop
FileStream.Close()
NetworkStream.Close()
End If
End Sub)
WorkerThread.Start()
End Sub

Related

File locked after encryption

I have a small app that is designed to go through a folder and encrypt all the files and delete the non-encrypted version. The encryption works correctly but when I go to delete the file it is locked. Once the app is closed the file is no longer locked. My code is
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim path As String = Directory.GetCurrentDirectory()
Dim parent As DirectoryInfo = Directory.GetParent(path)
Dim completions As String = parent.FullName & "\Attachments_Completions"
Dim di As New DirectoryInfo(completions)
Dim fi As FileInfo() = di.GetFiles()
Dim dra As FileInfo
For Each dra In fi
If dra.Name <> "Completions.txt" And dra.Name <> "Attachments.txt" Then
Dim tmpFileName As String = String.Format("{0}\qqzr_{1}", dra.DirectoryName, dra.Name)
Dim encryptedName As String = String.Format("{0}\{1}", dra.DirectoryName, dra.Name)
FileSystem.Rename(String.Format("{0}\{1}", dra.DirectoryName, dra.Name), String.Format("{0}\qqzr_{1}", dra.DirectoryName, dra.Name))
cryptFile(tmpFileName, encryptedName, False)
File.Delete(tmpFileName)
End if
Next
End Sub
Sub cryptFile(ByVal sInputFilename As String, ByVal sOutputFilename As String, ByVal switch As Boolean)
' * Used to Encrypt or Decrypt a file
' ***********************************
Dim sKey As String = "a2#R|+~"
Try
Dim DES As New DESCryptoServiceProvider()
DES.Key() = ASCIIEncoding.ASCII.GetBytes(sKey)
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey)
'Read the input file into array
Dim fsInput As New FileStream(sInputFilename, FileMode.Open, FileAccess.Read)
Dim bytearrayinput(fsInput.Length - 1) As Byte
fsInput.Read(bytearrayinput, 0, bytearrayinput.Length)
'Define the crypto transformer
Dim cryptoTransform As ICryptoTransform
If switch Then
cryptoTransform = DES.CreateEncryptor()
Else
cryptoTransform = DES.CreateDecryptor
End If
'Create the encrypting streams
Dim fsEncrypted As New FileStream(sOutputFilename, FileMode.Create, FileAccess.Write)
Dim cryptostream As New CryptoStream(fsEncrypted, cryptoTransform, CryptoStreamMode.Write)
'Write the output file
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length)
cryptostream.Close()
cryptostream.Dispose()
'Release the input file
fsInput.Close()
fsInput.Dispose()
'Release the output file
fsEncrypted.Close()
fsEncrypted.Dispose()
Catch ex As Exception
End Try
End Sub
End Class
Can anyone help?
Cheers
James
Just add this
Catch ex As Exception
Debug.Write(ex.Message)
End Try
...and see what happens...
Thanks for the responses.
I have managed to resolve the problem by adding File.SetAttributes(tmpFileName, FileAttributes.Normal) before the File.Delete command

Client to client direct chat through server vb.net

Using socket programming, I'm developing a chatting application using vb.net. I have manage to established group chat using a server and multi-client. Now i want to establish a client to client direct chat through server and want to list down all connected clients. If anyone can guide me would be very helpful.
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim clientsList As New Hashtable
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
clientsList(dataFromClient) = clientSocket
broadcast(dataFromClient + " Joined ", dataFromClient, False)
msg(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
End While
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, _
ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = _
broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
'Dim infiniteCounter As Integer
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
While (True)
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
End Class
End Module

Pass data/parameter to socket thread using VB Net

am running two TCP servers(one in 50010 and other in 10250) in my code both in separate thread
Private Sub frmMainScreen_Load(ByVal eventSender As Object, ByVal eventArgs As EventArgs) Handles MyBase.Load
Dim Local_PortNum As String = Read_GlobalINI_File("TCP-IP CONFIGURATION", "LOCAL_PORT", "TCPIP_Config")
Read_FileLocation()
Dim s As New ClsAutomation_TcpClient
Dim t As New ClsAutomation_TcpClient
trd = New Thread(Sub() s.Main()) ' listens 55000 port
trd1 = New Thread(Sub() t.Main())' listens 10250 port
trd.IsBackground = True
trd.Start()
trd1.IsBackground = True
trd1.Start()
End Sub
here is my tcpserver class
Public Class ClsAutomation_TcpClient
Dim clientsList As New Hashtable
Public WithEvents status_bar1 As System.Windows.Forms.Label
Sub Main()
Dim serverSocket As New TcpListener(IPAddress.Any, 10250)
Dim clientSocket As TcpClient
Dim counter As Integer
Dim clientIPAddress As String
serverSocket.Start()
MsgBox("Chat Server Started ....")
counter = 0
While (True)
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim networkStream As NetworkStream = clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
Dim ipend As Net.IPEndPoint = clientSocket.Client.RemoteEndPoint
clientIPAddress = ipend.Address.ToString()
clientsList(clientIPAddress) = clientSocket
broadcast(clientIPAddress + " Joined ", dataFromClient, False)
' MsgBox(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
End While
clientSocket.Close()
serverSocket.Stop()
MsgBox("exit")
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
MsgBox(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
End Class
Public Class handleClinet
Public WithEvents status_bar1 As System.Windows.Forms.Label
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub broadcast(ByVal msg As String, ByVal uName As String, ByVal flag As Boolean)
'Dim Item As DictionaryEntry
'For Each Item In clientsList
Dim broadcastSocket As TcpClient
'broadcastSocket = CType(Item.Value, TcpClient)
broadcastSocket = Me.clientSocket
Dim broadcastStream As NetworkStream = broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
'Next
End Sub
Private Sub doChat()
'Dim infiniteCounter As Integer
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
While (True)
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
'MsgBox("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End While
End Sub
End Class
Here what i need to do is send data from a btn_click to the (trd) 55000 instance thread...
how would i do it
Your question is quite broad but in simple terms:
You need to create a NetworkStream object.
Assign this using the TcpClient.GetStream method and then call NetworkStream.Write
Something like this (untested) code:
Dim stream as NetworkStream
stream = clientSocket.GetStream
Dim buffer() as byte = System.Text.Encoding.ASCII.GetBytes("hello")
If stream.CanWrite Then stream.Write(buffer, 0, buffer.Length)

vb.net multi thread chat client and server

i have created a chat server for chatting. there i connect the client pc's that will allow to chat them. In my case, server allow me to connect with that, but i can't able to chat with others make use of my application. Please see my code and correct it. here is my code.
Client side code:
Imports System.Net.Sockets
Imports System.Text
Public Class Form1
Dim clientSocket As New System.Net.Sockets.TcpClient()
Dim serverStream As NetworkStream
Dim readData As String
Dim infiniteCounter As Integer
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox2.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
End Sub
Private Sub msg()
If Me.InvokeRequired Then
Me.Invoke(New MethodInvoker(AddressOf msg))
Else
TextBox1.Text = TextBox1.Text + Environment.NewLine + " >> " + readData
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
readData = "Conected to Chat Server ..."
msg()
clientSocket.Connect("192.168.1.215", 8888)
'Label1.Text = "Client Socket Program - Server Connected ..."
serverStream = clientSocket.GetStream()
Dim outStream As Byte() = _
System.Text.Encoding.ASCII.GetBytes(TextBox3.Text + "$")
serverStream.Write(outStream, 0, outStream.Length)
serverStream.Flush()
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf getMessage)
ctThread.Start()
End Sub
Private Sub getMessage()
For infiniteCounter = 1 To 2
infiniteCounter = 1
serverStream = clientSocket.GetStream()
Dim buffSize As Integer
Dim inStream(10024) As Byte
buffSize = clientSocket.ReceiveBufferSize
serverStream.Read(inStream, 0, buffSize)
Dim returndata As String = _
System.Text.Encoding.ASCII.GetString(inStream)
readData = "" + returndata
msg()
Next
End Sub
End Class
server side Code:
Imports System.Net.Sockets
Imports System.Text
Module Module1
Dim clientsList As New Hashtable
Sub Main()
Dim serverSocket As New TcpListener(8888)
Dim clientSocket As TcpClient
Dim infiniteCounter As Integer
Dim counter As Integer
serverSocket.Start()
msg("Chat Server Started ....")
counter = 0
infiniteCounter = 0
For infiniteCounter = 1 To 2
infiniteCounter = 1
counter += 1
clientSocket = serverSocket.AcceptTcpClient()
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
clientsList(dataFromClient) = clientSocket
broadcast(dataFromClient + " Joined ", dataFromClient, False)
msg(dataFromClient + " Joined chat room ")
Dim client As New handleClinet
client.startClient(clientSocket, dataFromClient, clientsList)
Next
clientSocket.Close()
serverSocket.Stop()
msg("exit")
Console.ReadLine()
End Sub
Sub msg(ByVal mesg As String)
mesg.Trim()
Console.WriteLine(" >> " + mesg)
End Sub
Private Sub broadcast(ByVal msg As String, _
ByVal uName As String, ByVal flag As Boolean)
Dim Item As DictionaryEntry
For Each Item In clientsList
Dim broadcastSocket As TcpClient
broadcastSocket = CType(Item.Value, TcpClient)
Dim broadcastStream As NetworkStream = _
broadcastSocket.GetStream()
Dim broadcastBytes As [Byte]()
If flag = True Then
broadcastBytes = Encoding.ASCII.GetBytes(uName + " says : " + msg)
Else
broadcastBytes = Encoding.ASCII.GetBytes(msg)
End If
broadcastStream.Write(broadcastBytes, 0, broadcastBytes.Length)
broadcastStream.Flush()
Next
End Sub
Public Class handleClinet
Dim clientSocket As TcpClient
Dim clNo As String
Dim clientsList As Hashtable
Public Sub startClient(ByVal inClientSocket As TcpClient, _
ByVal clineNo As String, ByVal cList As Hashtable)
Me.clientSocket = inClientSocket
Me.clNo = clineNo
Me.clientsList = cList
Dim ctThread As Threading.Thread = New Threading.Thread(AddressOf doChat)
ctThread.Start()
End Sub
Private Sub doChat()
Dim infiniteCounter As Integer
Dim requestCount As Integer
Dim bytesFrom(10024) As Byte
Dim dataFromClient As String
Dim sendBytes As [Byte]()
Dim serverResponse As String
Dim rCount As String
requestCount = 0
For infiniteCounter = 1 To 2
infiniteCounter = 1
Try
requestCount = requestCount + 1
Dim networkStream As NetworkStream = _
clientSocket.GetStream()
networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize))
dataFromClient = System.Text.Encoding.ASCII.GetString(bytesFrom)
dataFromClient = _
dataFromClient.Substring(0, dataFromClient.IndexOf("$"))
msg("From client - " + clNo + " : " + dataFromClient)
rCount = Convert.ToString(requestCount)
broadcast(dataFromClient, clNo, True)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Next
End Sub
End Class
End Module
One, you need to specify your PUBLIC IP address, second, you need to open port 8888 on your router.
Change: clientSocket.Connect("192.168.1.215", 8888) to:
clientSocket.Connect("", 8888)
And make sure to forward port 8888 to your internal LAN IP: 192.168.1.215
Also this is entirely unsecure, I would encrypt and decrypt the strings using triple DES. A little bit of security but at least its security.
Learn a bit about networking bud.

Save binary file from SQL Server

I'm trying to save a binary file stored in a SQL database with a SaveDialog, the function RetrieveFile retrieves the specified file from the database as a Byte array, here's what I have so far:
Private Shared Function RetrieveFile(ByVal filename As String) As Byte()
Dim connection As New SqlConnection("Data Source=SERVER\SQL2008;Initial Catalog=NorthPole;Integrated Security=True")
Dim command As New SqlCommand("SELECT pcfFile FROM Items WHERE pcfFileName=#Filename", connection)
command.Parameters.AddWithValue("#Filename", filename)
connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader(System.Data.CommandBehavior.SequentialAccess)
reader.Read()
Dim memory As New MemoryStream()
Dim startIndex As Long = 0
Const ChunkSize As Integer = 256
While True
Dim buffer As Byte() = New Byte(ChunkSize - 1) {}
Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
memory.Write(buffer, 0, CInt(retrievedBytes))
startIndex += retrievedBytes
If retrievedBytes <> ChunkSize Then
Exit While
End If
End While
connection.Close()
Dim data As Byte() = memory.ToArray()
memory.Dispose()
Return data
End Function
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "PCF File|*.pcf|"
saveFileDialog1.Title = "Save an pcf File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
Dim fs As System.IO.FileStream = CType(RetrieveFile("FakePCF.pcf"), System.IO.FileStream)
fs.Close()
End If
End Sub
Files are saved as "SqlDbType.VarBinary" within the database.
I get: "Index was outside the bounds of the array." on:
Dim retrievedBytes As Long = reader.GetBytes(1, startIndex, buffer, 0, ChunkSize)
The MemoryStream appears to not be retrieving the data yet the SQL sytax is correct.
What am I doing wrong?
Well, first of all, your method returns byte[] and you're trying to cast it to FileStream. You should change your handler to following:
Private Sub SaveAsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveAsToolStripMenuItem.Click
Dim saveFileDialog1 As New SaveFileDialog()
saveFileDialog1.Filter = "PCF File|*.pcf|"
saveFileDialog1.Title = "Save an pcf File"
saveFileDialog1.ShowDialog()
If saveFileDialog1.FileName <> "" Then
Dim fs As New System.IO.FileStream (saveFileDialog1.FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write)
Dim data As Byte() = RetrieveFile("FakePCF.pcf")
fs.Write(data, 0, data.Length)
fs.Flush()
fs.Close()
End If
End Sub