how to send a file in client/server using socket?

shohoku

Active member
Joined
Jun 15, 2005
Messages
31
Programming Experience
Beginner
in the chatting app
userA want to send a file to userB
can anyone tell me how to do it in VB.NET by using socket??
thanks~~~
 
client:
VB.NET:
Dim filebuffer As Byte()
Dim fileStream As Stream
fileStream = File.OpenRead(<file source>)
' Alocate memory space for the file
ReDim filebuffer(fileStream.Length)
fileStream.Read(filebuffer, 0, fileStream.Length)
' Open a TCP/IP Connection and send the data
Dim clientSocket As New TcpClient(<servers name or IPAddress>, <socket>)
Dim networkStream As NetworkStream
networkStream = clientSocket.GetStream()
networkStream.Write(filebuffer, 0, fileStream.Length)

sorry i cant seem to get my server to work, but maybe this will give you an idea
 
Server side

hederimiller said:
client:
VB.NET:
Dim filebuffer As Byte()
Dim fileStream As Stream
fileStream = File.OpenRead(<file source>)
' Alocate memory space for the file
ReDim filebuffer(fileStream.Length)
fileStream.Read(filebuffer, 0, fileStream.Length)
' Open a TCP/IP Connection and send the data
Dim clientSocket As New TcpClient(<servers name or IPAddress>, <socket>)
Dim networkStream As NetworkStream
networkStream = clientSocket.GetStream()
networkStream.Write(filebuffer, 0, fileStream.Length)

sorry i cant seem to get my server to work, but maybe this will give you an idea


What is Server Side for save file in disk ?
 
There are no comments, but you should be able to understand what is going on. In the event that you do not understand something, just let me know and I will try to explain. Both codes are in there own Thread, so it should be no problem for you are anyone to add to they projects. Don’t forget to make the proper declaration (or name change). I do have an extra section Just for sending the name and file size. It’s the same thing as chatting, but also scanning for special key words “Name:” and “FileSize:”. Then from there it is just a matter of sending and receiving (while suspending chat or opening up a new connection) the value of those two. If you want to see my code for that too then let me know.

You have to add both codes to the client (sending and receiving) and the server (sending and receiving) so that both can send and receive files.

Sending!
VB.NET:
Private Sub SendFile()
With OpenFileDialog1
.CheckFileExists = True
.Title = ""
.ShowDialog()
End With
 
Dim IP As String = InputBox("Enter the IP address or hostname of you traget!", _
"IP Address", "127.0.0.1")
Client = New TcpClient
Client.Connect(IP, 1234)
Dim NWStream As NetworkStream = Client.GetStream
Dim bytesToSend(Client.SendBufferSize) As Byte
Dim FI As New FileInfo(OpenFileDialog1.FileName)
ProgressBar1.Maximum = FI.Length
Dim FileSTR As New FileStream(OpenFileDialog1.FileName, FileMode.Open, FileAccess.Read)
Dim FileReader As New BinaryReader(FileSTR)
Dim numBytesRead As Integer
Dim Ipos As Integer
 
Do Until Ipos >= FI.Length
numBytesRead = FileSTR.Read(bytesToSend, 0, bytesToSend.Length)
NWStream.Write(bytesToSend, 0, numBytesRead)
Ipos = Ipos + numBytesRead
ProgressBar1.Value += numBytesRead
ProgressBar1.Update()
NWStream.Flush()
Loop
 
Threading.Thread.Sleep(1000)
ProgressBar1.Value = 0
NWStream.Flush()
FileSTR.Close()
FileReader.Close()


Receiving!
VB.NET:
Private Sub ReceiveFile()
Try
Dim Client As TcpClient = TCP.AcceptTcpClient()
Dim NWStream As NetworkStream = client.GetStream
Dim bytesToRead(client.ReceiveBufferSize) As Byte
Dim numBytesRead As Integer 
Dim BUFFER_SIZE As Integer = client.ReceiveBufferSize
Dim FileSTR As New FileStream(TextBox1.Text, FileMode.Append, FileAccess.Write)
 
Do
numBytesRead = 0
numBytesRead = NWStream.Read(bytesToRead, 0, BUFFER_SIZE)
FileSTR.Write(bytesToRead, 0, numBytesRead)
Bytes = Bytes + numBytesRead
StatusBarPanel1.Text = "Downloaded: " & Bytes & " KB."
Loop Until numBytesRead = 0
 
FileSTR.Close()
NWStream.Close()
Client.Close()
MsgBox("All done!")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
 
REcThread = New Threading.Thread(AddressOf RF)
REcThread.Start()
End Sub
Good Luck!
 
Sorry, but I can’t understand the website since it’s not in English.

If I understand your question correctly, than you would like to know what is the difference between sending a String and a File right?

There are only two differences. The first one is how the File and String are converted; the second one is how it’s being sent.

If you want to send a String, this is how you would convert it to its Byte form.

VB.NET:
[COLOR=blue][FONT=Courier New]Dim[/FONT][/COLOR][FONT=Courier New] SendBytes [COLOR=blue]As[/COLOR] [COLOR=blue]Byte[/COLOR]() = [COLOR=blue]New[/COLOR] [COLOR=blue]Byte[/COLOR]() {}[/FONT]
[FONT=Courier New]SendBytes = Encoding.ASCII.GetBytes(TextBox1.Text)[/FONT]

Then after it is converted, you would then use a sample UDP socket to send it to its destination.

VB.NET:
[FONT=Courier New]UDPClient.Send(SendBytes, SendBytes.Length)[/FONT]

Whereas for a File (object), you would have to convert it to its Binary Form, than send it using a Network Stream after loading it byte by byte into memory. Then depending on the size of the File, you are going to have to put it in a loop so that it can keep sending the File. Same thing for the server, you are going to have to loop it until the entire file is received.

I hope I answered your question!
 
It's always going to be different since the client or server doesn’t send or receiving a file and a String using the same method (which I think I explain above).

BUT, if you are talking about the code from the link that you provide, then I could not really understand it since it’s not in English, but going by the structure of the code and some calls that I recognized. Then he/she (the author of the code) is using a TCP Socket which will require you to create the “Send” command (routine). That routine can be created using the Network Stream (which is what I used in the pervious example to send and receive a file). The only difference would then have to be the method of conversion (String à Encoded Bytes VS. File à Binary Data (also bytes)) and the “loop” for sending and receiving large files VS. sending and receiving a String(s) through one “block of data”.

If this explanation does not answer your question, then provide a detailed example of what you're trying to understand.
 
Ho i can extend here server recibe the file ?

Private Sub LeerSocket()
Dim IDReal As Net.IPEndPoint 'ID del cliente que se va a escuchar
Dim Recibir() As Byte 'Array utilizado para recibir los datos que llegan
Dim InfoClienteActual As InfoDeUnCliente 'Informacion del cliente que se va escuchar
Dim Ret As Integer = 0

IDReal = IDClienteActual
InfoClienteActual = Clientes(IDReal)

With InfoClienteActual

While True
If .Socket.Connected Then
Recibir = New Byte(100) {}

Try
'Me quedo esperando a que llegue un mensaje desde el cliente
Ret = .Socket.Receive(Recibir, Recibir.Length, SocketFlags.None)

If Ret > 0 Then
'Guardo el mensaje recibido
.UltimosDatosRecibidos = Encoding.ASCII.GetString(Recibir)
Clientes(IDReal) = InfoClienteActual

'Genero el evento de la recepcion del mensaje
RaiseEvent DatosRecibidos(IDReal)
Else
'Genero el evento de la finalizacion de la conexion
RaiseEvent ConexionTerminada(IDReal)
Exit While
End If

Catch e As Exception
If Not .Socket.Connected Then
'Genero el evento de la finalizacion de la conexion
RaiseEvent ConexionTerminada(IDReal)
Exit While
End If
End Try
End If
End While

Call CerrarThread(IDReal)
End With
End Sub


Any idea ?
 
Here it is!

I’ am currently working on a second version of this project. It will accept more than one client and it will be all TCP socket. This current version is a mix between UDP sockets and TCP sockets. As soon as I finish the second version, I will notify you, but only if you want me too.

There is also a bug in the version. You are only allowed to send one file per startup. I think this might be because of where I made some declarations. As soon as I fix it I will send you it or post up an updated version in this thread.

No credits are necessary!

Good Luck!
 

Attachments

  • File Transfer.zip
    104.3 KB · Views: 726
Last edited:
I' am currently working on a TCP only, and yes it does send String (Chat) and data (file).
 
Back
Top