using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace AsyncClient
{
public partial class Connect : System.Windows.Forms.Form
{
public string client_ip;
byte[] m_DataBuffer = new byte[10];
IAsyncResult m_asynResult;
public AsyncCallback pfnCallBack;
public Socket m_socClient;
public AsyncCallback pfnWorkerCallBack;
public Socket m_socListener;
public Socket m_socWorker;
private System.Windows.Forms.TextBox txtPort;
private System.Windows.Forms.Button cmdSend;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Button cmdConnect;
private System.Windows.Forms.Button cmdClose;
private System.Windows.Forms.TextBox txtIPAddr;
int port;
string file;
public Connect()
{
InitializeComponent();
FTServerCode.receivedPath = "";
}
private void EnableCommands(bool abEnableConnect)
{
button1.Enabled = abEnableConnect;
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
private void button1_Click(object sender, EventArgs e)
{
try
{
EnableCommands(true);
//create the socket instance...
m_socClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// get the remote IP address...
client_ip = comboBox1.SelectedItem.ToString();
string myIP = System.Net.Dns.GetHostByName(comboBox1.SelectedItem.ToString()).AddressList[0].ToString();
IPAddress ip = IPAddress.Parse(myIP);
/* if (comboBox2.SelectedItem.Equals("Default"))
{
port = 8221;
}
else
MessageBox.Show("Port not available");*/
int iPortNo = 8444;
//create the end point
IPEndPoint ipEnd = new IPEndPoint(ip.Address, iPortNo);
//connect to the remote host...
m_socClient.Connect(ipEnd);
EnableCommands(false);
//watch for data ( asynchronously )...
//groupBox1.Visible = false;
groupBox2.Visible = true;
WaitForData();
//Chat_Window frm = new Chat_Window();
//frm.Show();
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
EnableCommands(true);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (m_socClient != null)
{
//m_socClient.Shutdown (SocketShutdown.Send);
m_socClient.Close();
m_socClient = null;
EnableCommands(true);
MessageBox.Show("All Connections are Disconnected");
}
}
private void button4_Click(object sender, EventArgs e)
{
try
{
Object objData = textBox2.Text;
textBox1.Text = textBox1.Text + "\r\nME-> " + textBox2.Text + "\r\n";
textBox2.Text = "";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
m_socClient.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//File
private void button5_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open your File";
//openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
file = openFileDialog1.FileName.ToString();
}
try
{
IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656);
/* Make IP end point same as Server. */
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
/* Make a client socket to send data to server. */
string filePath = "";
/* File reading operation. */
file = file.Replace("\\", "/");
while (file.IndexOf("/") > -1)
{
filePath += file.Substring(0, file.IndexOf("/") + 1);
file = file.Substring(file.IndexOf("/") + 1);
}
byte[] fileByte = Encoding.ASCII.GetBytes(file);
if (fileByte.Length > 850 * 1024)
{
//curMsg = "File size is more than 850kb, please try with small file.";
return;
}
// curMsg = "Buffering ...";
byte[] fileData = File.ReadAllBytes(filePath + file);
/* Read & store file byte data in byte array. */
byte[] clientData = new byte[4 + fileByte.Length + fileData.Length];
/* clientData will store complete bytes which will store file name length, file name & file data. */
byte[] fileLen = BitConverter.GetBytes(fileByte.Length);
/* File name length’s binary data. */
fileLen.CopyTo(clientData, 0);
fileByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileByte.Length);
/* copy these bytes to a variable with format line [file name length][file name] [ file content] */
// curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);
//Trying to connection with server. /
// curMsg = "File sending...";
clientSock.Send(clientData);
/* Now connection established, send client data to server. */
//curMsg = "Disconnecting...";
clientSock.Close();
/* Data send complete now close socket. */
// curMsg = "File transferred.";
}
catch (Exception ex)
{
//if(ex.Message=="No connection could be made because the target machine actively refused it")
// curMsg="File Sending fail. Because server not running." ;
//else
// curMsg = "File Sending fail." + ex.Message;
}
}
/// <summary>
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button7_Click(object sender, EventArgs e)
{
}
/// <summary>
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Connect_Load_1(object sender, EventArgs e)
{
//create a new NetworkBrowser object, and get the
//list of network computers it found, and add each
//entry to the combo box on this form
try
{
NetworkBrowser nb = new NetworkBrowser();
foreach (string pc in nb.getNetworkComputers())
{
// Show the IP
//MessageBox.Show(myIP);
comboBox1.Items.Add(pc);
}
}
catch (Exception ex)
{
MessageBox.Show("An error occurred trying to access the network computers", "error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
//Application.Exit();
}
///////////WaitFor connection
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8444);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect1), null);
button8.Enabled = false;
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
/////Wait File transfer
try
{
if (FTServerCode.receivedPath.Length > 0)
backgroundWorker1.RunWorkerAsync();
else
MessageBox.Show("Please select file receiving path");
}
catch (SocketException se)
{
MessageBox.Show("Connection Error");
}
}
/// <summary>
/// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button3_Click(object sender, EventArgs e)
{
//HOME frm = new HOME();
//frm.Show();
if (m_socClient != null)
{
//m_socClient.Shutdown (SocketShutdown.Send);
m_socClient.Close();
m_socClient = null;
//EnableCommands(true);
}
}
/// <summary>
/// //////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public void WaitForData()
{
try
{
if (pfnCallBack == null)
{
pfnCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = m_socClient;
// now start to listen for any data...
m_asynResult = m_socClient.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnCallBack, theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
textBox1.Text =textBox1.Text + "\r\nFag04-> "+szData+"\r\n";
WaitForData();
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
/*private void cmdListen_Click(object sender, System.EventArgs e)
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint ( IPAddress.Any ,8221);
//bind to local IP Address...
m_socListener.Bind( ipLocal );
//start listening...
m_socListener.Listen (4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback( OnClientConnect ),null);
cmdListen.Enabled = false;
}
catch(SocketException se)
{
MessageBox.Show ( se.Message );
}
}*/
/* private void button8_Click(object sender, EventArgs e)
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8444);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect1), null);
button8.Enabled = false;
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
*/
private void button2_Click_1(object sender, EventArgs e)
{
try
{
Object objData = txtDataTx.Text;
txtDataRx.Text = txtDataRx.Text + "ME-> " + txtDataTx.TabIndex + "\r\n";
txtDataTx.Text = "";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
m_socWorker.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
/* private void button2_Click_1(object sender, EventArgs e)
{
try
{
Object objData = txtDataTx.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
m_socWorker.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
*/
//server
public void OnClientConnect1(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept(asyn);
WaitForData1(m_socWorker);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public class CSocketPacket1
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public void WaitForData1(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived1);
}
CSocketPacket1 theSocPkt = new CSocketPacket1();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnDataReceived1(IAsyncResult asyn)
{
try
{
CSocketPacket1 theSockId = (CSocketPacket1)asyn.AsyncState;
//end receive...
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
textBox1.Text = textBox1.Text + szData;
WaitForData1(m_socWorker);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
/// <summary>
/// File Transfer Server
/// </summary>
/*private void button9_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
FTServerCode.receivedPath = fd.SelectedPath;
}
}*/
/*private void button10_Click(object sender, EventArgs e)
{
if (FTServerCode.receivedPath.Length > 0)
backgroundWorker1.RunWorkerAsync();
else
MessageBox.Show("Please select file receiving path");
}*/
private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = FTServerCode.receivedPath;
label3.Text = FTServerCode.curMsg;
}
FTServerCode obj = new FTServerCode();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
obj.StartServer();
}
private void button11_Click(object sender, EventArgs e)
{
FileDialog fDg = new OpenFileDialog();
if (fDg.ShowDialog() == DialogResult.OK)
{
FTClientCode.SendFile(fDg.FileName,client_ip);
}
}
private void recievingPathToolStripMenuItem_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
FTServerCode.receivedPath = fd.SelectedPath;
backgroundWorker1.RunWorkerAsync();
}
}
private void button10_Click(object sender, EventArgs e)
{
try
{
if (FTServerCode.receivedPath.Length > 0)
backgroundWorker1.RunWorkerAsync();
else
MessageBox.Show("Please select file receiving path");
}
catch (SocketException se)
{
MessageBox.Show("Connection Error");
}
}
private void button9_Click(object sender, EventArgs e)
{
FolderBrowserDialog fd = new FolderBrowserDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
FTServerCode.receivedPath = fd.SelectedPath;
backgroundWorker1.RunWorkerAsync();
}
}
}
class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656);
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
public static string receivedPath;
public static string curMsg = "Stopped";
public void StartServer()
{
try
{
curMsg = "Starting...";
sock.Listen(100);
curMsg = "Running and waiting to receive file.";
Socket clientSock = sock.Accept();
byte[] clientData = new byte[1024 * 5000];
int receivedBytesLen = clientSock.Receive(clientData);
curMsg = "Receiving data...";
int fileNameLen = BitConverter.ToInt32(clientData, 0);
string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
BinaryWriter bWrite = new BinaryWriter(File.Open(receivedPath + "/" + fileName, FileMode.Append)); ;
bWrite.Write(clientData, 4 + fileNameLen, receivedBytesLen - 4 - fileNameLen);
curMsg = "Saving file...";
bWrite.Close();
clientSock.Close();
curMsg = "Reeived & Saved file; Server Stopped.";
}
catch (Exception ex)
{
curMsg = "File Receving error.";
}
}
}
/// <summary>
/// File Transfer Client
/// </summary>
class FTClientCode
{
public static string curMsg = "Idle";
public static void SendFile(string fileName,string dest_ip)
{
try
{
string myIP = System.Net.Dns.GetHostByName(dest_ip).AddressList[0].ToString();
IPAddress ip = IPAddress.Parse(myIP);
//IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
IPEndPoint ipEnd = new IPEndPoint(ip.Address, 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
string filePath = "";
fileName = fileName.Replace("\\", "/");
while (fileName.IndexOf("/") > -1)
{
filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
fileName = fileName.Substring(fileName.IndexOf("/") + 1);
}
byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
if (fileNameByte.Length > 850 * 1024)
{
curMsg = "File size is more than 850kb, please try with small file.";
return;
}
curMsg = "Buffering ...";
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);
curMsg = "Connection to server ...";
clientSock.Connect(ipEnd);
curMsg = "File sending...";
clientSock.Send(clientData);
curMsg = "Disconnecting...";
clientSock.Close();
curMsg = "File transferred.";
}
catch (Exception ex)
{
if (ex.Message == "No connection could be made because the target machine actively refused it")
curMsg = "File Sending fail. Because server not running.";
else
curMsg = "File Sending fail." + ex.Message;
}
}
}
}