adhokshaj

FTP and Chat Client

Apr 23rd, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.40 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Net.Sockets;
  4. using System.Windows.Forms;
  5.  
  6. namespace WinClient_CS
  7. {
  8.     public partial class Form1 : Form
  9.     {
  10.         private string partialStr;
  11.         private System.Net.IPHostEntry ips = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
  12.         const int PORTNO = 500;
  13.         const int FTPPORTNO = 501;
  14.         const string SERVERIP = "127.0.0.1";
  15.         private TcpClient client;
  16.         private byte[] data;
  17.         private System.IO.FileStream fs;
  18.         private string filename;
  19.         private string fullfilename;
  20.  
  21.         public Form1()
  22.         {
  23.             InitializeComponent();
  24.         }
  25.  
  26.         public void ReceiveMessage(IAsyncResult ar)
  27.         {
  28.             try
  29.             {
  30.                 int bytesRead;
  31.                 bytesRead = client.GetStream().EndRead(ar);
  32.                 if (bytesRead < 1)
  33.                 {
  34.                     return;
  35.                 }
  36.                 else
  37.                 {
  38.                     string messageReceived;
  39.                     int i = 0;
  40.                     int start = 0;
  41.                     while (data[i] != 0)
  42.                     {
  43.                         if (i + 1 > bytesRead)
  44.                         {
  45.                             break;
  46.                         }
  47.                         if (data[i] == 10)
  48.                         {
  49.                             messageReceived = partialStr + System.Text.Encoding.ASCII.GetString(data, start, i - start) + Environment.NewLine;
  50.                             object[] para = { messageReceived };
  51.                             this.Invoke(new delUpdateHistory((this.UpdateHistory)), para);
  52.                             start = i + 1;
  53.                         }
  54.                         i += 1;
  55.                     }
  56.  
  57.                     if (start != i)
  58.                     {
  59.                         partialStr = System.Text.Encoding.ASCII.GetString(data, start, i - start);
  60.                     }
  61.                 }
  62.                 client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(client.ReceiveBufferSize), ReceiveMessage, null);
  63.             }
  64.             catch (Exception ex)
  65.             {
  66.                 MessageBox.Show(ex.ToString());
  67.             }
  68.         }
  69.  
  70.         public void Disconnect()
  71.         {
  72.             try
  73.             {
  74.                 client.GetStream().Close();
  75.                 client.Close();
  76.             }
  77.             catch (Exception ex)
  78.             {
  79.                 MessageBox.Show(ex.ToString());
  80.             }
  81.         }
  82.  
  83.         public void SendMessage(string message)
  84.         {
  85.             message += "\n";
  86.             try
  87.             {
  88.                 System.Net.Sockets.NetworkStream ns;
  89.                 lock (client.GetStream())
  90.                 {
  91.                     ns = client.GetStream();
  92.                     byte[] bytesToSend = System.Text.Encoding.ASCII.GetBytes(message);
  93.                     ns.Write(bytesToSend, 0, bytesToSend.Length);
  94.                 }
  95.             }
  96.             catch (Exception ex)
  97.             {
  98.                 MessageBox.Show(ex.ToString());
  99.             }
  100.         }
  101.  
  102.         public delegate void delUpdateHistory(string str);
  103.  
  104.         public void UpdateHistory(string str)
  105.         {
  106.             if (str.StartsWith("[Join]"))
  107.             {
  108.                 int nameLength = str.IndexOf("]", 6);
  109.                 lstUsers.Items.Add(str.Substring(7, nameLength - 7));
  110.                 return;
  111.             }
  112.             else if (str.StartsWith("[Left]"))
  113.             {
  114.                 int nameLength = str.IndexOf("]", 6);
  115.                 try
  116.                 {
  117.                     lstUsers.Items.RemoveAt(lstUsers.Items.IndexOf(str.Substring(7, nameLength - 7)));
  118.                 }
  119.                 catch (Exception ex)
  120.                 {
  121.                 }
  122.                 return;
  123.             }
  124.             else if (str.StartsWith("[Usrs]"))
  125.             {
  126.                 string[] users = str.Substring(7, str.Length - 8).Split(',');
  127.                 lstUsers.Items.Clear();
  128.                 foreach (string user in users)
  129.                 {
  130.                     lstUsers.Items.Add(user);
  131.                 }
  132.                 lstUsers.Items.RemoveAt(lstUsers.Items.Count - 1);
  133.                 return;
  134.             }
  135.             else if (str.StartsWith("[File]"))
  136.             {
  137.                 string[] users = str.Substring(7, str.IndexOf("]", 7) - 7).Split(',');
  138.                 int index = str.IndexOf("]", 7) + 2;
  139.                 string filename = str.Substring(index, str.Length - index - 3);
  140.                 DialogResult response;
  141.                 response = MessageBox.Show("Do you want to download the file " + filename, "Download", MessageBoxButtons.YesNo);
  142.                 if (response == DialogResult.Yes)
  143.                 {
  144.                     SendMessage("[Send_File][" + users[0] + "," + txtNick.Text + "]");
  145.                     FTP_Receive(filename);
  146.                 }
  147.                 return;
  148.             }
  149.             else if (str.StartsWith("[Send_File]"))
  150.             {
  151.                 string userIP = str.Substring(12, str.Length - 15);
  152.                 FTP_Send(fullfilename, userIP);
  153.                 return;
  154.             }
  155.             else if (str.StartsWith("[Talk]"))
  156.             {
  157.                 str = str.Substring(str.IndexOf("]", 7) + 1);
  158.                 txtMessageHistory.AppendText(str);
  159.             }
  160.         }
  161.  
  162.         private void btnSignIn_Click(object sender, EventArgs e)
  163.         {
  164.             if (btnSignIn.Text == "Sign In")
  165.             {
  166.                 try
  167.                 {
  168.                     client = new TcpClient();
  169.                     client.Connect(SERVERIP, PORTNO);
  170.  
  171.                     data = new byte[client.ReceiveBufferSize];
  172.                     SendMessage("[Join][" + txtNick.Text + "]");
  173.                     client.GetStream().BeginRead(data, 0, System.Convert.ToInt32(client.ReceiveBufferSize), ReceiveMessage, null);
  174.                     btnSignIn.Text = "Sign Out";
  175.                     btnSend.Enabled = true;
  176.                     txtNick.Enabled = false;
  177.                     System.Threading.Thread.Sleep(500);
  178.                     SendMessage("[Usrs]");
  179.                 }
  180.                 catch (Exception ex)
  181.                 {
  182.                     MessageBox.Show(ex.ToString());
  183.                 }
  184.             }
  185.             else
  186.             {
  187.                 Disconnect();
  188.                 lstUsers.Items.Clear();
  189.                 btnSignIn.Text = "Sign In";
  190.                 btnSend.Enabled = false;
  191.                 txtNick.Enabled = true;
  192.             }
  193.         }
  194.  
  195.         private void btnSend_Click(object sender, EventArgs e)
  196.         {
  197.             if (lstUsers.SelectedItems.Count < 1)
  198.             {
  199.                 MessageBox.Show("You must select who to chat with.");
  200.                 return;
  201.             }
  202.             string Message = "[Talk][";
  203.  
  204.             foreach (object user in lstUsers.SelectedItems)
  205.             {
  206.                 Message += user + ",";
  207.             }
  208.             Message += "]" + txtNick.Text + ">" + txtMessage.Text;
  209.             txtMessageHistory.Text += txtNick.Text + ">" + txtMessage.Text + Environment.NewLine;
  210.             SendMessage(Message);
  211.             txtMessage.Clear();
  212.         }
  213.  
  214.         private void btnFTP_Click(object sender, EventArgs e)
  215.         {
  216.             string Message = "[File][" + txtNick.Text + ",";
  217.  
  218.             if (lstUsers.SelectedItems.Count < 1)
  219.             {
  220.                 MessageBox.Show("You must select who to send to.");
  221.                 return;
  222.             }
  223.             foreach (object user in lstUsers.SelectedItems)
  224.             {
  225.                 Message += user + ",";
  226.             }
  227.             OpenFileDialog openFileDialog1 = new OpenFileDialog();
  228.             openFileDialog1.InitialDirectory = "c:\\";
  229.             openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
  230.             openFileDialog1.FilterIndex = 2;
  231.             openFileDialog1.RestoreDirectory = true;
  232.             if (openFileDialog1.ShowDialog() == DialogResult.OK)
  233.             {
  234.                 fullfilename = openFileDialog1.FileName;
  235.                 filename = fullfilename.Substring(fullfilename.LastIndexOf("\\") + 1);
  236.                 Message += "][" + filename + "]";
  237.                 SendMessage(Message);
  238.             }
  239.         }
  240.  
  241.         public void FTP_Send(string filename, string recipientIP)
  242.         {
  243.             System.Net.Sockets.TcpClient tcpClient = new System.Net.Sockets.TcpClient();
  244.             tcpClient.Connect(recipientIP, FTPPORTNO);
  245.             int BufferSize = tcpClient.ReceiveBufferSize;
  246.             NetworkStream nws = tcpClient.GetStream();
  247.             FileStream fs;
  248.             fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
  249.             byte[] bytesToSend = new byte[fs.Length];
  250.             int numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length);
  251.             int totalBytes = 0;
  252.             for (int i = 0; i <= fs.Length / BufferSize; i++)
  253.             {
  254.                 if (fs.Length - (i * BufferSize) > BufferSize)
  255.                 {
  256.                     nws.Write(bytesToSend, i * BufferSize, BufferSize);
  257.                     totalBytes += BufferSize;
  258.                 }
  259.                 else
  260.                 {
  261.                     nws.Write(bytesToSend, i * BufferSize, (int)fs.Length - (i * BufferSize));
  262.                     totalBytes += (int)fs.Length - (i * BufferSize);
  263.                 }
  264.                 ToolStripStatusLabel1.Text = "Sending " + totalBytes + " bytes....";
  265.                 Application.DoEvents();
  266.             }
  267.             ToolStripStatusLabel1.Text = "Sending " + totalBytes + " bytes....Done.";
  268.             fs.Close();
  269.             tcpClient.Close();
  270.         }
  271.  
  272.         public void FTP_Receive(string filename)
  273.         {
  274.             try
  275.             {
  276.                 System.Net.IPAddress localAdd = System.Net.IPAddress.Parse(ips.AddressList[0].ToString());
  277.                 System.Net.Sockets.TcpListener listener = new System.Net.Sockets.TcpListener(localAdd, FTPPORTNO);
  278.                 listener.Start();
  279.                 TcpClient tcpClient = listener.AcceptTcpClient();
  280.                 NetworkStream nws = tcpClient.GetStream();
  281.                 if (File.Exists("H:\\chat_file\\" + filename))
  282.                 {
  283.                     File.Delete("H:\\chat_file\\" + filename);
  284.                 }
  285.                 fs = new System.IO.FileStream("H:\\chat_file\\" + filename, FileMode.Append, FileAccess.Write);
  286.                 int counter = 0;
  287.                 int totalBytes = 0;
  288.                 do
  289.                 {
  290.                     int bytesRead = nws.Read(data, 0, tcpClient.ReceiveBufferSize);
  291.                     totalBytes += bytesRead;
  292.                     fs.Write(data, 0, bytesRead);
  293.                     ToolStripStatusLabel1.Text = "Receiving " + totalBytes + " bytes....";
  294.                     Application.DoEvents();
  295.                     counter += 1;
  296.                 } while (!(!(nws.DataAvailable)));
  297.                 ToolStripStatusLabel1.Text = "Receiving " + totalBytes + " bytes....Done.";
  298.                 fs.Close();
  299.                 tcpClient.Close();
  300.                 listener.Stop();
  301.             }
  302.             catch (Exception ex)
  303.             {
  304.                 MessageBox.Show(ex.ToString());
  305.             }
  306.         }
  307.  
  308.         private void Form_Closing(object sender, FormClosingEventArgs e)
  309.         {
  310.             Disconnect();
  311.         }
  312.     }
  313. }
Advertisement
Add Comment
Please, Sign In to add comment