I have this code but it's not working...
The progressbar is not moving and the downloaded file size is 0kb.
I think I have some problem in my WHILE loop! How can I solve this problem? Please give me instructions!
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DirectoryInfo folder= new DirectoryInfo(#"C:\Cloud24");
try
{
{
long size= 0;
WebClient request = new WebClient();
request.Credentials = new NetworkCredential(userid, userpass);
FileStream file = File.Create(folder+ "//" + downloadname);
byte[] filedata = request.DownloadData(ftpadress + "/" + downloadname);
while ((size= file.Read(filedata, 0, filedata.Length)) > 0)
{
file.Write(filedata, 0, filedata.Length);
size += (int)filedata.Length;
double dProgressPercentage = ((double)(size) / (double)filedata.Length);
backgroundWorker1.ReportProgress((int)(dProgressPercentage * 100));
}
file.Close();
MessageBox.Show(downloadname + " downloaded!" +
Environment.NewLine + "There: " + folder);
}
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
}
}
This should probably work, but I haven't actually tested it.
private async void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var folder = new DirectoryInfo(#"C:\Cloud24");
try
{
{
var manualResetEvent = new ManualResetEventSlim();
var client = new WebClient { Credentials = new NetworkCredential(userid, userpass) };
client.DownloadProgressChanged += (o, args) => backgroundWorker1.ReportProgress(args.ProgressPercentage);
client.DownloadDataCompleted += (o, args) => manualResetEvent.Set();
var filedata = client.DownloadDataAsync(ftpadress + "/" + downloadname);
manualResetEvent.Wait();
using (var stream = File.Create(folder + "//" + downloadname))
{
await stream.WriteAsync(filedata, 0, filedata.Length);
}
MessageBox.Show(downloadname + " downloaded!" + Environment.NewLine + "There: " + folder);
}
}
catch (Exception exc)
{
MessageBox.Show("Error: " + exc.Message);
}
}
Related
i'm trying to do globalexceptionhandling, i've already tried 3 methods to do this but nothing caught an exception thrown somewhere in the program
static void Main()
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Catch);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(Catch);
try
{
Application.Instance.Start();
}
catch (Exception ex)
{
StackTrace st = new StackTrace(ex, true);
StackFrame[] frames = st.GetFrames();
List<string> errorList = new List<string>();
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var frame in frames)
{
errorList.Add("PC-Name: " + System.Environment.MachineName + "\nIP: " + host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) + "\nUser-Name: " + Application.Instance.LoggedInTester.LastName + " " + Application.Instance.LoggedInTester.FirstName + "\nDateiname: " + frame.GetFileName() + "\nMethode: " + frame.GetMethod().Name + "\nZeile: " + frame.GetFileLineNumber() + "\n\n");
}
SyslogMessage msg = new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault());
SyslogUdpSender sender = new SyslogUdpSender("localhost", 514);
sender.Send(new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault()), new SyslogRfc3164MessageSerializer());
}
}
static void Catch(object sender, System.Threading.ThreadExceptionEventArgs e)
{
StackTrace st = new StackTrace(e.Exception, true);
StackFrame[] frames = st.GetFrames();
List<string> errorList = new List<string>();
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var frame in frames)
{
errorList.Add("PC-Name: " + System.Environment.MachineName + "\nIP: " + host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) + "\nUser-Name: " + Application.Instance.LoggedInTester.LastName + " " + Application.Instance.LoggedInTester.FirstName + "\nDateiname: " + frame.GetFileName() + "\nMethode: " + frame.GetMethod().Name + "\nZeile: " + frame.GetFileLineNumber() + "\n\n");
}
SyslogMessage msg = new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault());
SyslogUdpSender send = new SyslogUdpSender("localhost", 514);
send.Send(new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault()), new SyslogRfc3164MessageSerializer());
}
static void Catch(object sender, UnhandledExceptionEventArgs e)
{
StackTrace st = new StackTrace((Exception)e.ExceptionObject, true);
StackFrame[] frames = st.GetFrames();
List<string> errorList = new List<string>();
IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var frame in frames)
{
errorList.Add("PC-Name: " + System.Environment.MachineName + "\nIP: " + host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork) + "\nUser-Name: " + Application.Instance.LoggedInTester.LastName + " " + Application.Instance.LoggedInTester.FirstName + "\nDateiname: " + frame.GetFileName() + "\nMethode: " + frame.GetMethod().Name + "\nZeile: " + frame.GetFileLineNumber() + "\n\n");
}
SyslogMessage msg = new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault());
SyslogUdpSender send = new SyslogUdpSender("localhost", 514);
send.Send(new SyslogMessage(DateTime.Now, Facility.SecurityOrAuthorizationMessages1, Severity.Warning, host.AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork).ToString(), "Prüfmittelüberwachung", errorList.FirstOrDefault()), new SyslogRfc3164MessageSerializer());
}
this is what i've already tried, nothing caught the exception.
and i'm not using the standard application.run method, i'm using a singleton class to start from, where for every view(form) i have a presenter gets created in which the view gets created
does anyone know how to do globalexception handling with this setup?
also, sorry for my bad english
best regards
EDIT: MVCE
namespace Application
{
static class Program
{
static void Main()
{
System.Windows.Forms.Application.EnableVisualStyles();
System.Windows.Forms.Application.SetCompatibleTextRenderingDefault(false);
System.Windows.Forms.Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Catch);
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(Catch);
try
{
Application.Instance.Start();
}
catch (Exception ex)
{
//do some catching
}
}
static void Catch(object sender, System.Threading.ThreadExceptionEventArgs e)
{
//do some catching
}
static void Catch(object sender, UnhandledExceptionEventArgs e)
{
//do some catching
}
}
public class Application
{
private static Application _instance;
private Application()
{
}
public static Application Instance
{
get
{
return _instance ?? (_instance = new Application());
}
}
internal void Start()
{
StartOverviewWindow();
}
private void StartOverviewWindow()
{
throw new Exception();
}
}
}
As a quick answer (because I can't find duplicates for all of those), to handle
an exception thrown somewhere
you have to handle following events:
Application.ThreadException += ...
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += ...
// tasks exceptions, add in app.config:
// <runtime>
// <ThrowUnobservedTaskExceptions enabled="true"/>
// </runtime>
TaskScheduler.UnobservedTaskException += ...
For difference between Application.ThreadException and AppDomain.CurrentDomain.UnhandledException see this.
TcpServer.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Server
{
public class TcpServer
{
static ServerGUI serverGUI;
private const Int32 PORT = 13000;
private const String ADDRESS = "127.0.0.1";
private IPAddress localAddress;
public TcpListener tcpServer;
private static Byte[] bytes;
private static String data;
static DateTime localDate;
static String cultureName = "de-DE";
static CultureInfo cultureInfo;
private static int clientCount = 0;
private const char SEPERATOR = '|';
static NetworkStream stream;
public TcpServer()
{
serverGUI = new ServerGUI();
serverGUI.Show();
cultureInfo = new CultureInfo(cultureName);
BackgroundWorker worker1 = new BackgroundWorker();
worker1.DoWork += new DoWorkEventHandler(Worker1_DoWork);
worker1.RunWorkerAsync();
}
private void Worker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
{
localAddress = IPAddress.Parse(ADDRESS);
tcpServer = new TcpListener(localAddress, PORT);
localDate = DateTime.Now;
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") chatserver has started.\n");
tcpServer.Start();
while (true)
{
TcpClient client = await tcpServer.AcceptTcpClientAsync();
ThreadPool.QueueUserWorkItem(ThreadProc, client);
}
}));
}
catch (SocketException socketEx)
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
{
serverGUI.AddOutput(socketEx.Message + "\n");
}));
}
catch (Exception ex)
{
serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(delegate ()
{
serverGUI.AddOutput(ex.Message + "\n");
}));
}
finally
{
if (tcpServer != null)
{
tcpServer.Stop();
}
}
}
private static async void ThreadProc(object obj)
{
await serverGUI.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal, (ThreadStart)(async delegate ()
{
var client = (TcpClient)obj;
bytes = new Byte[256];
data = null;
// Get a stream object for reading and writing
stream = client.GetStream();
int i = 0;
while (true)
{
if (stream.CanRead)
{
i = await stream.ReadAsync(bytes, 0, bytes.Length);
}
localDate = DateTime.Now;
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
string[] receivedStr = data.Split(SEPERATOR);
byte[] msg = null;
if (receivedStr != null && receivedStr[0] == "new")
{
clientCount++;
msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Welcome, " + receivedStr[2] + "! - active users: " + clientCount);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") new client recognized!\n");
serverGUI.AddOutput(" " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
serverGUI.AddOutput(" " + "active clients: " + clientCount + "\n\n");
}
else if (receivedStr != null && receivedStr[0] == "close")
{
clientCount--;
msg = System.Text.Encoding.ASCII.GetBytes("chatserver" + SEPERATOR + "Goodbye, " + receivedStr[2] + "! - active users: " + clientCount);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
serverGUI.AddOutput("(" + localDate.ToString("g", cultureInfo) + ") client disconnected!\n");
serverGUI.AddOutput(" " + receivedStr[1] + " - Nickname: " + receivedStr[2] + "\n");
serverGUI.AddOutput(" " + "active clients: " + clientCount + "\n\n");
client.Close();
break;
}
else
{
msg = System.Text.Encoding.ASCII.GetBytes(data);
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
}
}));
}
}
}
(Client)MainWindow.xaml.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Client
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Int32 port = 13000;
private String hostname = "127.0.0.1";
public TcpClient tcpClient;
DateTime localDate;
String cultureName = "de-DE";
CultureInfo cultureInfo;
BackgroundWorker worker1;
NetworkStream stream;
bool work = false;
private const char SEPERATOR = '|';
public MainWindow()
{
InitializeComponent();
buttonDisconnect.IsEnabled = false;
textBoxServerIP.Text = "127.0.0.1:13000";
textBoxNickname.Text = "User";
cultureInfo = new CultureInfo(cultureName);
worker1 = new BackgroundWorker();
worker1.DoWork += Worker1_DoWork;
}
private void Worker1_DoWork(object sender, DoWorkEventArgs e)
{
this.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Background, (ThreadStart)(async delegate ()
{
try
{
while (work)
{
Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hallo");
data = new Byte[256];
// String to store the response ASCII representation.
String responseData = String.Empty;
// Read the first batch of the TcpServer response bytes.
Int32 bytes = 0;
if (stream.CanRead)
{
bytes = await stream.ReadAsync(data, 0, data.Length);
}
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
string[] receivedStr = responseData.Split(SEPERATOR);
if (receivedStr != null && receivedStr[0] == "chatserver")
{
textBoxChatRoom.Text += receivedStr[0] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[1] + "\n\n";
}
else if (receivedStr != null && receivedStr[0] == "msg")
{
textBoxChatRoom.Text += receivedStr[1] + " (" + localDate.ToString("g", cultureInfo) + "): " + receivedStr[2] + "\n";
}
else
{
textBoxChatRoom.Text += responseData + "\n\n";
}
}
}
catch (ArgumentNullException argumentNullEx)
{
textBoxChatRoom.Text += argumentNullEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (InvalidOperationException invalidOperationEx)
{
textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}));
}
private async void buttonConnect_Click(object sender, RoutedEventArgs e)
{
string[] connectionStr = { "" };
if (!textBoxServerIP.Text.Equals(null) && textBoxServerIP.Text != "")
{
connectionStr = textBoxServerIP.Text.Split(':');
try
{
hostname = connectionStr[0];
port = Int32.Parse(connectionStr[1]);
tcpClient = new TcpClient(connectionStr[0], Int32.Parse(connectionStr[1]));
//localDate = DateTime.Now;
textBoxChatRoom.Text += "Connecting to server " + connectionStr[0] + "...\n";
if (tcpClient.Connected)
{
textBoxChatRoom.Text += "Connected!\n";
textBoxServerIP.IsEnabled = false;
textBoxNickname.IsEnabled = false;
buttonConnect.IsEnabled = false;
buttonDisconnect.IsEnabled = true;
localDate = DateTime.Now;
stream = tcpClient.GetStream();
// Send the message to the connected TcpServer.
byte[] msg = System.Text.Encoding.ASCII.GetBytes("new" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
work = true;
worker1.RunWorkerAsync();
}
else
{
textBoxChatRoom.Text += "not connected!\n";
}
}
catch (ArgumentNullException argumentNullExceptionEx)
{
textBoxChatRoom.Text += argumentNullExceptionEx.Message + "\n";
}
catch (ArgumentOutOfRangeException argumentOutOfRangeEx)
{
textBoxChatRoom.Text += argumentOutOfRangeEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (FormatException formatEx)
{
textBoxChatRoom.Text += formatEx.Message + "\n";
}
catch (OverflowException overflowEx)
{
textBoxChatRoom.Text += overflowEx.Message + "\n";
}
catch (CultureNotFoundException cultureNotFoundEx)
{
textBoxChatRoom.Text += cultureNotFoundEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}
else
{
textBoxChatRoom.Text += "Please enter serverip!\n";
}
}
private async void buttonDisconnect_Click(object sender, RoutedEventArgs e)
{
work = false;
buttonConnect.IsEnabled = true;
textBoxServerIP.IsEnabled = true;
textBoxNickname.IsEnabled = true;
buttonDisconnect.IsEnabled = false;
byte[] msg = System.Text.Encoding.ASCII.GetBytes("close" + SEPERATOR + textBoxServerIP.Text.ToString() + SEPERATOR + textBoxNickname.Text.ToString());
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
private void buttonExit_Click(object sender, RoutedEventArgs e)
{
Environment.Exit(0);
}
private async void buttonSend_Click(object sender, RoutedEventArgs e)
{
try
{
// Send the message to the connected TcpServer.
byte[] msg = System.Text.Encoding.ASCII.GetBytes("msg" + SEPERATOR + textBoxNickname.Text.ToString() + SEPERATOR + textBoxSend.Text);
stream = tcpClient.GetStream();
if (stream.CanWrite)
{
await stream.WriteAsync(msg, 0, msg.Length);
}
}
catch (ArgumentNullException argumentNullEx)
{
textBoxChatRoom.Text += argumentNullEx.Message + "\n";
}
catch (SocketException socketEx)
{
textBoxChatRoom.Text += socketEx.Message + "\n";
}
catch (InvalidOperationException invalidOperationEx)
{
textBoxChatRoom.Text += invalidOperationEx.Message + "\n";
}
catch (Exception ex)
{
textBoxChatRoom.Text += ex.Message + "\n";
}
}
}
}
The connection between server and clients functions but if I send something into the networkstream with one client, the other clients don't receive anything. This should be a little chatroom-WPF-application
I have a problem, that i couldn't receive and send between multiple clients and I don't know what I am doing wrong...
Please can somebody help...
I have a DotNetZip code for zipping the folder. It doesnt zip the file for the first time after cleaning the solution. After that it works fine. Can anybody know the issue why its happening??
Button Click Event Code
private void button3_Click(object sender, EventArgs e)
{
try
{
copy_stuff(textBox1.Text, textBox2.Text, textBox3.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Method that gets called from Button Click
private void copy_stuff(string srcFolder, string destFolder, string Backup)
{
using (ZipFile zip = new ZipFile())
{
zip.AddProgress += AddProgressHandler;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
zip.SaveProgress += SaveProgress;
zip.StatusMessageTextWriter = System.Console.Out;
zip.AddDirectory(destFolder);
zip.Save(Backup + "\\VibrantBackup" + DateTime.Now.ToString("yyyyMMdd hh.mm.ss") + ".zip");
label1.Text = "Compression completed.";
}
}
Add & Save Handlers for Progress
int _numEntriesToAdd = 0;
int _numEntriesAdded = 0;
void AddProgressHandler(object sender, AddProgressEventArgs e)
{
switch (e.EventType)
{
case ZipProgressEventType.Adding_Started:
_numEntriesToAdd = 0;
_numEntriesAdded = 0;
label1.Text = "Adding files to the zip...";
label1.Update();
Application.DoEvents();
break;
case ZipProgressEventType.Adding_AfterAddEntry:
_numEntriesAdded++;
label1.Text = String.Format("Adding file: {0} :: {2}",
_numEntriesAdded, _numEntriesToAdd, e.CurrentEntry.FileName);
label1.Update();
Application.DoEvents();
break;
case ZipProgressEventType.Adding_Completed:
label1.Text = "Added all files";
label1.Update();
Application.DoEvents();
break;
}
}
public void SaveProgress(object sender, SaveProgressEventArgs e)
{
if (e.EventType == ZipProgressEventType.Saving_Started)
{
label1.Text = "Begin Saving: " + e.ArchiveName;
label1.Update();
Application.DoEvents();
}
else if (e.EventType == ZipProgressEventType.Saving_BeforeWriteEntry)
{
label1.Text = "Processing : " + e.CurrentEntry.FileName;
label1.Update();
label3.Text = "Files Processed: (" + (e.EntriesSaved + 1) + "/" + e.EntriesTotal + ")";
label3.Update();
Application.DoEvents();
progressBar3.Maximum = e.EntriesTotal;
progressBar3.Value = e.EntriesSaved + 1;
}
else if (e.EventType == ZipProgressEventType.Saving_EntryBytesRead)
{
//progressBar2.Value = (int)((e.BytesTransferred * 100) / e.TotalBytesToTransfer);
//label3.Text = "Writing: " + e.CurrentEntry.FileName + " (" + (e.EntriesSaved + 1) + "/" + e.EntriesTotal + ")";
label1.Update();
Application.DoEvents();
}
}
I'm new to sockets so I tried to create a server and a client that exchange messages. I created one in C# but it gave me weird error which it once I start the server it freezes and "not responding" message appears ... same happens with client when I connect the server but the problem is when I close any of them .. the other application have the updates shown up so idk what the problem is anyways here are the codes U used
Server class
Socket Soc;
static ushort MaxClients = 1000;
static List<Socket> ClientList = new List<Socket>(MaxClients);
static bool ServerStarted;
public Server()
{
InitializeComponent();
button1.Enabled = false;
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e) // Send
{
string MessageToSend = textBox1.Text;
byte[] Buffer = Encoding.Default.GetBytes(MessageToSend);
foreach (var client in ClientList)
{
Soc.Send(Buffer, 0, Buffer.Length, SocketFlags.None);
}
textBox2.Text += " Message Sent To Clients : " + MessageToSend + Environment.NewLine;
}
private void button3_Click(object sender, EventArgs e) // Start
{
StartServer("25.21.113.163", 5000);
}
private void button2_Click(object sender, EventArgs e) // Stop
{
CloseServer();
}
private void button4_Click(object sender, EventArgs e) // Exit
{
CloseServer();
Application.Exit();
}
public void StartServer(string Ip, ushort Port)
{
Soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Soc.Bind(new IPEndPoint(IPAddress.Parse(Ip), Port));
textBox2.Text += " Server Is Created On Ip : " + Ip + ", Port : " + Port + Environment.NewLine;
Soc.Listen(MaxClients);
textBox2.Text += " Server Is Listening to Clients Now... " + Environment.NewLine;
ServerStarted = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
ReceiveData();
}
public void ReceiveData()
{
while (true)
{
var Client = Soc.Accept();
ClientList.Add(Client);
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
textBox2.Text += " Client Located At Ip : " + Client.RemoteEndPoint.ToString().Split(':')[0].ToString() + " Is Now Connected To Server " + Environment.NewLine;
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedDataLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string MessageFromClient = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedDataLength);
textBox2.Text += " Message Sent to Server : " + MessageFromClient + Environment.NewLine;
}
}
}
public void CloseServer()
{
Soc.Close();
ServerStarted = false;
textBox2.Text += " Server Is Closed Now... " + Environment.NewLine;
button3.Enabled = true;
button2.Enabled = false;
button1.Enabled = false;
}
Client class
Socket Client;
public Form1()
{
InitializeComponent();
button1.Enabled = false;
button2.Enabled = false;
}
private void button1_Click(object sender, EventArgs e) // Send
{
string MessageToSend = textBox2.Text;
byte[] Buffer = Encoding.Default.GetBytes(MessageToSend);
Client.Send(Buffer, 0, Buffer.Length, SocketFlags.None);
textBox1.Text += " Sent Message To Server Is : " + MessageToSend + Environment.NewLine;
}
private void button2_Click(object sender, EventArgs e) // LogOut
{
ClientClose();
}
private void button3_Click(object sender, EventArgs e) // Connect
{
ConnectToServer("25.21.113.163", 5000);
}
private void button4_Click(object sender, EventArgs e) // Exit
{
ClientClose();
Application.Exit();
}
public void ConnectToServer(string Ip, ushort Port)
{
try
{
Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Client.Connect(Ip, Port);
textBox1.Text += " You Are Now Connected To Server Hosted On Ip : " + Client.RemoteEndPoint + Environment.NewLine;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = false;
ReceiveData();
}
catch
{
textBox1.Text += " Server In Offline Now " + Environment.NewLine;
}
}
public void ReceiveData()
{
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedBytesLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string ReceivedMessage = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedBytesLength);
textBox1.Text += " Received Message From Server Is : " + ReceivedMessage + Environment.NewLine;
}
}
public void ClientClose()
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = true;
Client.Dispose();
Client.Close();
textBox1.Text += " You Are Disconnected From Server" + Environment.NewLine;
}
I'd like to know what did I do wrong? And how can I get rid of that silly "Not Responding" state of both applications?
First, Let's make a corrections on your code so that it works, thank I'd give some Asynchronous Socket tutorials which is a lot easier than Synchronous.
Your problem is in this line:
public void ReceiveData()
{
while (true)
{
var Client = Soc.Accept();
ClientList.Add(Client);
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
textBox2.Text += " Client Located At Ip : " + Client.RemoteEndPoint.ToString().Split(':')[0].ToString() + " Is Now Connected To Server " + Environment.NewLine;
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedDataLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string MessageFromClient = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedDataLength);
textBox2.Text += " Message Sent to Server : " + MessageFromClient + Environment.NewLine;
}
}
}
This is because of 2 reasons:
1) You must listen to incoming connection to a separate thread.
2) You must listen to each client in a separate thread too, so they don't block each other. In your example second while(true) which is listening for client is blocking server socket from accepting other clients. Refactor it to:
public void ReceiveData()
{
new Thread(() =>
{
while (true)
{
var Client = Soc.Accept();
ClientList.Add(Client);
label3.Text = ClientList.Count.ToString() + "/" + MaxClients;
textBox2.Text += " Client Located At Ip : " + Client.RemoteEndPoint.ToString().Split(':')[0].ToString() + " Is Now Connected To Server " + Environment.NewLine;
new Thread(() =>
{
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedDataLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string MessageFromClient = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedDataLength);
textBox2.Text += " Message Sent to Server : " + MessageFromClient + Environment.NewLine;
}
}).Start();
}
}).Start();
}
This approach uses separate thread for each client to process received data from client.
I also added code for client app:
public void ReceiveData()
{
new Thread(() =>
{
while (true)
{
byte[] ReceivedBytes = new byte[1024];
int ReceivedBytesLength = Client.Receive(ReceivedBytes, 0, ReceivedBytes.Length, SocketFlags.None);
string ReceivedMessage = Encoding.Default.GetString(ReceivedBytes, 0, ReceivedBytesLength);
textBox1.Text += " Received Message From Server Is : " + ReceivedMessage + Environment.NewLine;
}
}).Start();
}
In the future have a look Asynchronous Sockets and you will no more need handling multithreading issues.
http://msdn.microsoft.com/en-us/library/fx6588te.aspx
http://msdn.microsoft.com/en-us/library/bbx2eya8.aspx
EDIT Updated client/ser
I did what #Enigmativity write
here it is:
Action<int, ProgressBar, Label, Label, int, Button> downloadFileAsync = (i, pb, label2, label1, ServID, button1) =>
{
var bd = AppDomain.CurrentDomain.BaseDirectory;
var fn = bd + "/" + i + ".7z";
var down = new WebClient();
DownloadProgressChangedEventHandler dpc = (s, e) =>
{
label1.Text = "Download Update: " + i + " From: " + ServID;
int rec =Convert.ToInt16(e.BytesReceived / 1024);
int total =Convert.ToInt16(e.TotalBytesToReceive / 1024) ;
label2.Text = "Downloaded: " + rec.ToString() + " / " + total.ToString() + " KB";
pb.Value = e.ProgressPercentage;
};
AsyncCompletedEventHandler dfc = null; dfc = (s, e) =>
{
down.DownloadProgressChanged -= dpc;
down.DownloadFileCompleted -= dfc;
CompressionEngine.Current.Decoder.DecodeIntoDirectory(AppDomain.CurrentDomain.BaseDirectory + "/" + i + ".7z", AppDomain.CurrentDomain.BaseDirectory);
File.Delete(fn);
if (i == ServID)
{
button1.Enabled = true;
label1.Text = "Game Is Up-To-Date.Have Fun!!";
label2.Text = "Done..";
}
down.Dispose();
};
My only problam now is when the program is extarting the downloaded file
CompressionEngine.Current.Decoder.DecodeIntoDirectory(AppDomain.CurrentDomain.BaseDirectory + "/" + i + ".7z", AppDomain.CurrentDomain.BaseDirectory);
In some files its take time to extarct the downloaded file
so how i can tell the program to wait until decompressing is complete?
Try defining a single lambda that will encapsulate a single async download and then call that in a loop.
Here's the lambda:
Action<int> downloadFileAsync = i =>
{
var bd = AppDomain.CurrentDomain.BaseDirectory;
var fn = bd + "/" + i + ".7z";
var wc = new WebClient();
DownloadProgressChangedEventHandler dpc = (s, e) =>
{
progressBar1.Value = e.ProgressPercentage;
};
AsyncCompletedEventHandler dfc = null;
dfc = (s, e) =>
{
wc.DownloadProgressChanged -= dpc;
wc.DownloadFileCompleted -= dfc;
CompressionEngine.Current.Decoder.DecodeIntoDirectory(fn, bd);
File.Delete(fn);
wc.Dispose();
};
wc.DownloadProgressChanged += dpc;
wc.DownloadFileCompleted += dfc;
wc.DownloadFileAsync(new Uri(Dlpath + i + "/" + i + ".7z"), fn);
};
You'll note that it nicely detaches all events and also correctly disposes of the WebClient instance.
Now call it like this:
while (i <= ServID)
{
downloadFileAsync(i);
i++;
}
You'll have to fiddle with the progress bar update to properly show the progress of all the files downloading, but in principle this should work for you.