Phase 3, Break communication
channel and release resources: When last
slice of byte data saved at server, client and server close the socket object
and release all resource like file stream, socket object etc.
For code url is:
Client Code:
[C#]
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Client_Socket
{
//FILE TRANSFER USING C#.NET SOCKET PROGRAMMING - CLIENT
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("That program can transfer small
file. I've test up to 850kb file");
IPAddress[] ipAddress =
Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
string fileName = "Your File Name";
string filePath = "Your File Path";
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
byte[] fileData = File.ReadAllBytes(filePath + fileName);
byte[] clientData = new byte[4 + fileNameByte.Length +
fileData.Length];
byte[] fileNameLen =
BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
clientSock.Connect(ipEnd);
clientSock.Send(clientData);
Console.WriteLine("File:{0} has been sent.",
fileName);
clientSock.Close();
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("File Sending fail." +
ex.Message);
}
}
}
}[Visual Basic]
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Net
Imports System.Net.Sockets
Imports System.IO
Namespace Client_Socket
'FILE TRANSFER USING C#.NET SOCKET PROGRAMMING- CLIENT
Class Program
Private Shared Sub Main(ByVal args As String())
Try
Console.WriteLine("That program can transfer small file. I've test up to 850kb file")
Dim ipAddress As IPAddress() = Dns.GetHostAddresses("localhost")
Dim ipEnd As New IPEndPoint(ipAddress(0), 5656)
Dim clientSock As New Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP)
Dim fileName As String = "Your File Name"
Dim filePath As String = "Your File Path"
Dim fileNameByte As Byte() = Encoding.ASCII.GetBytes(fileName)
Dim fileData As Byte() = File.ReadAllBytes(filePath + fileName)
Dim clientData As Byte() = New Byte(4 + fileNameByte.Length + (fileData.Length - 1)) {}
Dim fileNameLen As Byte() = BitConverter.GetBytes(fileNameByte.Length)
fileNameLen.CopyTo(clientData, 0)
fileNameByte.CopyTo(clientData, 4)
fileData.CopyTo(clientData, 4 + fileNameByte.Length)
clientSock.Connect(ipEnd)
clientSock.Send(clientData)
Console.WriteLine("File:{0} has been sent.", fileName)
clientSock.Close()
Console.ReadLine()
Catch ex As Exception
Console.WriteLine("File Sending fail." & ex.Message)
End Try
End Sub
End Class
End Namespace
No comments:
Post a Comment