I am trying to send multiple files to a server ever 2 seconds and after the file is sent it is deleted and the program is restarted as to again generate the file which needs again to be sent to server.
But it works till the time the server is online...In case the sever is restarted all the program functions will work fine but when this function is invoked it keeps on displaying "No connection could be made because the target machine actively refused it" no matter even when the server comes online in between..
private void sendfile()
{
timer.Stop();
RegistryKey theLocalMachine = Registry.LocalMachine;
RegistryKey theSystem2 = theLocalMachine.OpenSubKey(#"SOFTWARE\\NetworkUsagemonitoring\\", true);
RegistryKey interfacekey4 = theSystem2.OpenSubKey("Usagerecorder", true);
string serverno = interfacekey4.GetValue("serverno").ToString();
for (int i = 0; i < netarr1.Length; i++)
{
for (int j = 0; j < netarr2.Length; j++)
{
if (netarr1[i].Name == netarr2[j])
{
if (recorded[j] == 1)
{
try
{
IPEndPoint ipEnd = new IPEndPoint(IPAddress.Parse(serverno), 5656);
Socket clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
if (File.Exists(#"C:\" + netarr1[i].Name + "_record.xml"))
{
fileName = (#"C:\" + netarr1[i].Name + "_record.xml");
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)
{
return;
}
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);
clientSock.Close();
recorded[j] = 0;
File.Delete(#"C:\" + netarr1[i].Name + "_record.xml");
}
else
{
UpdateNetwork_Interface();
}
}
catch (Exception ex)
{
LogEvent("No connection could be made because the target machine actively refused it", EventLogEntryType.Information);
break;
}
finally
{
j++;
}
}
else
{
UpdateNetwork_Interface();
}
}
}
}
}
What i want is of the server goes offline or "No connection could be made because the target machine actively refused it" is displayed...the program should continue with the loop and move unhindered until server comes online and the updated file will be sent to the server.
Well, you're exception handling is faulty. You are catching (Exception ex) and printing out the error message you quoted. It's entirely possible that the ACTUALL exception has to do with the files you are writing and erasing. perhaps some files failed to erase or be opened.
Looking at the code, i suspect the problem is that you're never actually closing the socket if there is an exception.
You should add the following to the finally clause.
if (clientSocket!=null)
clientSocket.Close();
And you should print out the actual exception message to the error log so you know what's really going on when an error occurs.
Related
I am trying to write some string to a file, and here is the code:
private static void WriteSelfDefinedFile(string msg)
{
ArrayList logTypes = SelfDefinedLogRule(msg);
// New some StreamWriter here
StreamWriter[] sws = new StreamWriter[selfDefinedLogFileName.Length];
for(int i = 0;i<selfDefinedLogFileName.Length;i++)
{
sws[i] = new StreamWriter(selfDefinedLogDir + selfDefinedLogFileName[i], true);
Debug.Log("111");
}
// It is writting here, not important for this question,I think.
foreach(SelfDefinedLogType temp in logTypes)
{
int index = (int)temp;
foreach (SelfDefinedLogType n in Enum.GetValues(typeof(SelfDefinedLogType)))
{
if(temp == n && sws[index]!=null)
{
sws[index].WriteLine(System.DateTime.Now.ToString() + ":\t"+ msg);
break;
}
else if(sws[index] == null)
{
LogError("File " + selfDefinedLogFileName[index] + " open fail");
}
}
}
// Close the StreamWrite[] here
for(int i=0;i<selfDefinedLogFileName.Length;i++)
{
sws[i].Close();
Debug.Log("222");
}
}
When the client is sending msg to server or server replying some msg to client, this funtion will be called to write some message to some files.
And unity throws the IOException:Sharing violation on path D:\SelfDefinedLogs\SentAndReceiveMsg.txt, sometimes. I mean, it doesn't happened everytime I write.
I have closed all the opened streamWriter at the end of the funtion, but the problem still come up.I am really confused.I will be grateful if anybody gives some solutions to this problem.
I have a server-client socket chat application,
at the server folder I have a game folder where I have a javascript game that I wrote,pictures of the game, and an html page to run the game.
When the client writing the command "#game" the server will send him the game files, and the client will download the game files to a C directory.
I have tried to transfer the files in couple of ways all of them seem to fail, It's look like the html file and the JS files transfer completely but the pictures aren't complete and that's why the game isn't working...
I need to transfer the files using only sockets.
Server Side
I used the SendFile method and after every file data I sent "\d" for a sign to move to the next data so that client could know the different between files data.
public static bool Game(string msg, Socket socket)
{
if (msg.Equals("#game"))
{
ASCIIEncoding asc = new ASCIIEncoding();
string path = #"G:\הנדסת תוכנה\כיתה יא\ChatProject\ServerChat\game";
socket.Send(asc.GetBytes("#game"));
Byte[] preBuffer = asc.GetBytes("#download ");
Byte[] postBuffer = asc.GetBytes("#End");
socket.SendFile(path + #"\SpaceShip.js");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\page.html");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\background.jpg");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\defeat.png");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\enemyspaceship.png");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\friendlyspaceship.png");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\IMG_06062017_225026_0.png");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\laser.png");
socket.Send(asc.GetBytes(#"\d"));
socket.SendFile(path + #"\Images\victory.png");
socket.Send(asc.GetBytes(#"\d"));
Console.WriteLine("Game was send to "+socket.RemoteEndPoint);
return true;
}
return false;
}
Client Side
At the client side I first created the directory, and let myself to write the order of the files sending, at the Download function I moved every 2 char to check if I have the "\d" sign that I have sent, If I came across one I know it's the end of the data file and I write the data over the file I create.
public static void Game()
{
Console.WriteLine("downloading and opening the game...");
string path = #"C:\Game";
DirectoryInfo di = Directory.CreateDirectory(path);
di = Directory.CreateDirectory(path+#"\Images");
Console.WriteLine("The directory was created successfully ");
Console.WriteLine("reciving Data");
string[] pathArr = new string[]
{
path + #"\SpaceShip.js",
path + #"\page.html",
path + #"\Images\background.jpg",
path + #"\Images\defeat.png",
path + #"\Images\enemyspaceship.png",
path + #"\Images\friendlyspaceship.png",
path + #"\Images\IMG_06062017_225026_0.png",
path + #"\Images\laser.png",
path + #"\Images\victory.png"
};
Download(pathArr);
Console.WriteLine("Done!");
System.Diagnostics.Process.Start(path + #"\page.html");
}
public static void Download(string [] pathArr)
{
byte[] binDataIn = new byte[1025];
int k = socket.Receive(binDataIn, 0, 1025, SocketFlags.None);
ASCIIEncoding asc = new ASCIIEncoding();
string rcv = asc.GetString(binDataIn, 0, k);
string data = "";
int j = 0;
int i = 0;
while (j<=8)
{
string sign = rcv[i].ToString() + rcv[i + 1].ToString();
if (sign.Equals( #"\d"))
{
File.WriteAllText(pathArr[j], data);
data = "";
j++;
i += 2;
}
else
{
data += rcv[i];
i++;
}
if(rcv.Length-1<=i)
{
k = socket.Receive(binDataIn, 0, 1025, SocketFlags.None);
rcv = asc.GetString(binDataIn, 0, k);
i = 0;
}
}
}
I think I might complicated the process and there is a simpler way...
thanks to all the responding.
I've been developing a TCP server, and I require it to allow for the access of multiple clients at the same time.
I also require it to allow them to disconnect and reconnect whenever they wish and for whenever they send a TCP message for the logic to run behind it as well.
I have my basic code set up which allows for one user to be connected at once however, it doesn't allow for multiple clients.
Server Code - (First part, without logic)
IPAddress ipAd = IPAddress.Any;
TcpListener myList = new TcpListener(ipAd, 5001);
myList.Start();
Console.WriteLine("Waiting for a new connection");
Console.WriteLine("Last Connection From - " + client);
Console.Write("Stats - Errors: ");
Console.BackgroundColor = ConsoleColor.Red;
Console.Write(" " + Errors + " ");
Console.BackgroundColor = ConsoleColor.DarkCyan;
Console.WriteLine();
Console.WriteLine();
Console.Write(feed);
Socket s = myList.AcceptSocket();
client = Convert.ToString(s.RemoteEndPoint);
Console.Write(feed);
byte[] b = new byte[100];
int k = s.Receive(b);
Console.WriteLine("\n Message Recieved");
string msg = "";
for (int i = 0; i < k; i++)
{
msg = msg + Convert.ToChar(b[i]);
}
feed = feed + " \n " + msg;
There is also client code which, I'm not going to put in here because I don't believe it's needed. If you have any questions or improvements/modifications about the client just ask/tell me and I'll take a look.
I've been told there is ways of doing it through another thread but I haven't got a clue to how I would approach it.
I'm writing a part of a program that shall copy a batch of files from the current computer to a defined list of computers.
If these computers are not available, the code will hang for a long time trying to access them. Is there any functionallity in C# to check if the machine is available and then skip if it's not?
MFWs = File.ReadAllLines(GuiManager.MyConfigManagerConfig.MachinesList);
foreach (string MFW in MFWs)
{
if (MFW != System.Environment.MachineName)
{
String target = #"\\" + MFW + #"\D\IbSi\config\" + Path.GetFileName(ConfigFile);
String backup = #"\\" + MFW + #"\D\IbSi\userdata\" + Path.GetFileName(ConfigFile);
try
{
File.Copy(source, target, true);
File.Copy(source, backup, true);
}
catch (Exception ex)
{
Manager.SendMessage("Failed to copy " + Path.GetFileName(ConfigFile) + " to " + MFW + "\n" + ex.Message);
}
}
}
You could ping the computer before starting the copy (taken from this answer):
using System.Net.NetworkInformation;
public static bool IsHostAvailable(string nameOrAddress)
{
bool pingable = false;
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(nameOrAddress);
pingable = reply.Status == IPStatus.Success;
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
return pingable;
}
As noted in the comments you need to make sure the firewall on the servers is open for pings (ICMP echo requests)
I am writing a program that will live on a "Super PC" in my lab at work. Its job is to constantly query our customers databases proactively looking for common errors that we encounter.
It accomplishes this by using an adjustable timer and simply running down the list of queries and databases and interpreting the results.(Queries and Database connections are added using a Configuration UI)
This program has a TCP client/server connection with another app that I have written that lives on my team members personal machines. Messages get sent from the Server(Query) program to the client program alerting my team of errors found in the Databases.
The problem I keep encountering is occasionally a message gets sent through the socket at the exact same time a DB connection is made or a query is run and it causes the server program to crash with no explanation.
The methods that run the queries is always called in its own thread as well as the server connection is made in its own thread.
In addition I have placed all of the DB methods and Client Server methods in Try/Catch blocks that are setup to catch all exceptions and display the stack trace, but for some reason when it crashes its not hitting any of the catch.
The runQueries Methods is called off a C# .Net System.Timers.Timer which is supposed to launch a new thread on every tick.
Below are my Client/Server Methods and Query Methods
private void serverMeth()
{
try
{
/*conbox.Text = conbox.Text + "The server is running at port 8001..." + Environment.NewLine;
conbox.Text = conbox.Text + "The local End point is :" + myList.LocalEndpoint + Environment.NewLine;
conbox.Text = conbox.Text + "Waiting for a connection....." + Environment.NewLine;*/
msglist.Add("The server is running at port 8001...");
msglist.Add("The local end point is: " + myList.LocalEndpoint);
msglist.Add("Waiting for a connection...");
writeToLog("Listening for connection at "+myList.LocalEndpoint);
/* Start Listeneting at the specified port */
while (true)
{
gatherErrors();
myList.Start();
//Socket s = myList.AcceptSocket();
s = myList.AcceptSocket();
//conbox.Text = conbox.Text + "Connection accepted from " + s.RemoteEndPoint + Environment.NewLine;
msglist.Add("Connection accepted from " + s.RemoteEndPoint);
writeToLog("Connection Established #" + myList.LocalEndpoint);
byte[] b = new byte[20000];
int k = s.Receive(b);
//conbox.Text = conbox.Text + "Recieved..." + Environment.NewLine;
msglist.Add("Recieved...");
writeToLog("Message Recieved from Command Center");
//for (int i = 0; i < k; i++)
//{ conbox.Text = conbox.Text + Convert.ToChar(b[i]); }
string message = ""; //allows it to store the entire message in one line
string dt = DateTime.Now.ToString("MM-dd-yyyy hh:mm:ss");
string eid = "TEST ID";
for (int i = 0; i < k; i++)
{ message = message + Convert.ToChar(b[i]); }
if (message.Contains(uniquekey))
{
writeToLog("Message contains correct passcode");
message = message.Replace(uniquekey, "");
String[] splits = message.Split(',');
message = message.Replace("," + splits[1], "");
writeToLog("Connection from " + splits[1]);
msglist.Add(message); //this takes the completed message and adds it.
//DO IGNORE STUF HERE
if (!message.Equals(""))
{
//Message contains error key
Error erro = null;
for (int i = 0; i < errorss.Count; i++)
{
if (errorss[i].getKey().Equals(message)) {
erro = errorss[i];
}
}
Stage st = null;
if (erro != null)
{
for (int i = 0; i < stages.Count; i++)
{
if (stages[i].errContainCheck(erro))
{
st = stages[i];
}
}
}
if (st != null)
{
st.addIgnore(erro);
writeToLog("Error: " + erro.getKey() + "ignored");
}
}
//conbox.Text = conbox.Text + Environment.NewLine;
msglist.Add(" ");
string msg = "";
string log = "Error(s): ";
for (int i = 0; i < errorss.Count; i++)
{
msg += errorss[i].getTime() + "|"+errorss[i].getMsg()+"|" + errorss[i].getSite()+"|"+errorss[i].getKey();
msg += ",";
log += errorss[i].getKey()+",";
}
log+= "sent to Command Center";
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes(msg));
//conbox.Text = conbox.Text + "\nSent Acknowledgement" + Environment.NewLine;
msglist.Add("\nSent Acknowledgement");
writeToLog(log);
}
else
{
message = "Unauthorized access detected. Disregarding message.";
//.Add(message); //this takes the completed message and adds it.
//conbox.Text = conbox.Text + Environment.NewLine;
msglist.Add(" ");
writeToLog("Passcode mismatch");
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("Access Denied. Unique key mismatch."));
//conbox.Text = conbox.Text + "\nSent Acknowledgement" + Environment.NewLine;
msglist.Add("\nSent Denial Acknowledgement");
}
/* clean up */
s.Close();
myList.Stop();
if (quit == true)
{
break;
}
}
}
catch (Exception err)
{
//conbox.Text = conbox.Text + "Error..... " + err.StackTrace + Environment.NewLine;
msglist.Add("Error..... " + err.StackTrace);
writeToLog("ERROR: "+err.StackTrace);
}
}
private void sasDownload()
{
int selItemList;
selItemList = saerrlist.SelectedIndex;
saerrlist.Items.Clear(); //clears the list before redownload
saerrgrid.Rows.Clear();
try
{
TcpClient tcpclnt = new TcpClient();
//clibox.Text = clibox.Text + "Connecting....." + Environment.NewLine;
tcpclnt.Connect(staralertip.Text, 8001);
// use the ipaddress as in the server program
//clibox.Text = clibox.Text + "Connected" + Environment.NewLine;
//clibox.Text = clibox.Text + "Enter the string to be transmitted : " + Environment.NewLine;
String str = "982jsdf293jsadd02jkdas20dka2";
Stream stm = tcpclnt.GetStream();
if (ackClick)
{
str += ackKey;
ackClick = false;
}
String name = "User not found";
for (int i = 0; i < users.Count(); i++)
{
if(users[i].sys_id.Equals(SNLists.loggedinuser)){
name = users[i].name;
break;
}
}
str += "," + name;
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
//clibox.Text = clibox.Text + "Transmitting....." + Environment.NewLine;
stm.Write(ba, 0, ba.Length);
byte[] bb = new byte[20000];
int k = stm.Read(bb, 0, 20000);
string incmsg = "";
for (int i = 0; i < k; i++)
incmsg = incmsg + Convert.ToChar(bb[i]);
string tempmsg = "";
foreach (char c in incmsg)
{
if (c != ',')
{
tempmsg = tempmsg + c;
}
else if (c == ',')
{
saerrlist.Items.Add(tempmsg);
saerrgrid.Rows.Add(tempmsg.Split('|')[0], tempmsg.Split('|')[1], tempmsg.Split('|')[2], tempmsg.Split('|')[3]);
tempmsg = "";
}
}
saerrlist.Items.Add(tempmsg);
//saerrgrid.Rows.Add(tempmsg.Split('|')[0], tempmsg.Split('|')[1], tempmsg.Split('|')[2]);
//MessageBox.Show(incmsg);
tcpclnt.Close();
}
catch (Exception err)
{
//MessageBox.Show("Error..... " + err.StackTrace, "STAR Command Center: Connectivity Error");
staralertTimer.Enabled = false;
MessageBox.Show("Error downloading recent errors from STAR Alert System.\n\nPlease confirm STAR Alert is running " +
"and hit \"Refresh\" in the STAR Alert tab." + "\n" + err, "STAR Command Center: Connectivity Error");
}
saerrlist.SelectedIndex = selItemList;
}
public void runQueries()
{
OracleConnection con = new OracleConnection();
int siteNum = -1;
try
{
writeToLog("Call to runQueries");
List<List<Error>> results = new List<List<Error>>();
for (int i = 0; i < ppreset.getSites().Count(); i++)
{
siteNum = i;
Site s = ppreset.getSites()[i];
if (s.getStatus().Equals("ACTIVE"))
{
//OracleConnection con = new OracleConnection();
String it = "User Id=" + s.getLogin() + ";Password=" + s.getPassword() + ";Data Source=" + s.getDbName();
con.ConnectionString = it;
//con.OpenAsync();
con.Open();
writeToLog("Connection opened for site: " + s.getSite());
List<Error> subResults = new List<Error>();
for (int j = 0; j < s.getQueries().Count(); j++)
{
Query q = s.getQueries()[j];
string sql = q.getCode();
List<string> columns = getColumns(sql);
List<List<String>> mast = new List<List<String>>();
for (int m = 0; m < columns.Count(); m++)
{
mast.Add(new List<String>());
}
OracleCommand cmd = new OracleCommand(sql, con);
cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
writeToLog("Execute SQL, Begin Reading results...");
// dr.Read();
//List<String> results = new List<String>();
if (dr.HasRows)
{
//MessageBox.Show("has rows");
while (dr.Read())
{
//string result = "";
for (int p = 0; p < columns.Count(); p++)
{
if (columns.Count() != 0)
{
mast[p].Add(dr[columns[p]].ToString());
}
}
//results.Add(result);
}
}
subResults.AddRange(ruleCheck(mast, q.getRules(), s.getQueries()[j], ppreset.getSites()[i].getSite()));
cmd.Dispose();
writeToLog("Done reading");
}
results.Add(subResults);
// con.Dispose();
con.Close();
writeToLog("Connection Closed for site: " + s.getSite());
}
}
//we now have all of the error strings gathered from running all queries on all sites in the given preset
//lets send them to a method that will change the status' of the modules and makem RAVVEEEEE
//update(results);
if (errors == null && results.Count != 0)
{
//MessageBox.Show("errors = results");
errors = results;
writeToLog("First error found...errors = results");
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results[i].Count; j++)
{
if (foncig.lallerdisc == true)
{
sendLyncMsg(results[i][j].getMsg());
writeToLog("Lync Msg sent");
}
}
}
}
else
{
for (int i = 0; i < results.Count; i++)
{
for (int j = 0; j < results[i].Count; j++)
{
errors[i].Add(results[i][j]);
writeToLog("Error: " + results[i][j].getKey() + " added");
// MessageBox.Show("Error added to errors");
//////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
//LYNC STUFF CAN GO HERE///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
/////FOR EACH ERROR ADDED TO MASTER LIST SEND LYNC///////////////////////////
//////////////////////////////////////////////////////////////////////////////
if (foncig.lallerdisc == true)
{
sendLyncMsg(results[i][j].getMsg());
writeToLog("Lync msg sent");
}
}
}
}
}
catch (Exception e)
{//MessageBox.Show("Err: " + e);
badConn[siteNum] += "x";
writeToLog("Connection error strike added to " + ppreset.getSites()[siteNum].getSite());
con.Close();
checkForBadConn();
writeToLog( e.StackTrace);
}
//foncig.errors = errors;
//here we will check all of the errors in results against all of the errors in errors
//if the error is not in errors add it
//errors = results;
}
Query timer initialization
queryTimer = new System.Timers.Timer(120000);
queryTimer.Elapsed += queryTimer_Tick;
queryTimer.Enabled = true;
Tick method for query timer
private void queryTimer_Tick(object sender, EventArgs e)
{
GC.Collect();
try
{
runQueries();
}
catch (OracleException err)
{
// MessageBox.Show("Err: " + err);
}
}
How the server thread is started
server = new Thread(serverMeth);
server.Start();
Does anyone have any idea why this might be happening? Both programs work as described and do what they are supposed to its just when more and more clients begin connecting to the server it becomes more and more likely that a TCP connection and DB connection will occur at the same time.
Update 12:20 9/15/14
So I'm trying to upload a pic of the log from the last crash... but i don't have enough rep points... derp, anyway
This time the last line in the log is from a log purge(deletes log entries older than 24 hours)
However the program will only crash when I have the client program set to auto refresh. IE Client app has a button to request messages from server or user can select auto-refresh which sets request function to timer.
My only other thought is that multiple threads are trying to write to the log file at the same time, however my write to log method uses writeLinesAsync() so that shouldn't be a problem?
This issue turned out to be caused by multiple threads trying to write to the log file at the same time.
I resolved it by following #user469104's advice and creating an internal lock object to lock the writeToLog methods.
Both client and server apps have been running for multiple days now without breaking.
Thanks Everyone!