// Does necessary asynchronous work to initialize / connect RaspberryPi. // Note that this function might throw an exception when connection can't be established. private async Task Initialize() { try { Console.WriteLine("[x] Connecting to: " + this.endpoint.Address + " ..."); clientConnection = await ClientConn <Result, Request> .connectAsync(this.endpoint); // port usually 54321 /* Connection established, set IsConnected to true because async call returned. */ IsConnected = true; /* Fire the Connected event handler. Unused currently. */ Connected?.Invoke(this, EventArgs.Empty); } /* If host is offline, display the socket exception and stop running */ catch (SocketException sx) { IsConnected = false; Console.WriteLine("[ERROR] Connection couldn't be established. Host offline. ", sx); throw new SocketException(sx.ErrorCode); } /* If initialization fails, display the exception and stop running */ catch (Exception ex) { IsConnected = false; Console.WriteLine("[ERROR] Connection couldn't be established for unknown reasons."); throw new Exception("Connection couldn't be established for unknown reasons.", ex); } }
private void Awake() { Main = this; Obj_Conn = this.GetComponent <ClientConn>(); Auto = false; Debug.Log(Obj_Conn != null); }
/////////////////////////////////////////////////// // Member Functions /////////////////////////////////////////////////// /// <summary> /// Generic constructor /// </summary> public Database(ZoneServer server, ConfigSetting config, LogClient logger) { _server = server; _config = config; _conn = new ClientConn <Database>(new S2CPacketFactory <Database>(), this); _syncStart = new ManualResetEvent(false); _logger = logger; _conn._logger = logger; }
// Method: Request to add other user to room. public override void Serve() { // The title of the received packet will be request to add user to room. // The content of the received packet will be the name of the added user. // Preparing packet to be sent. Server.PacketSent.time = Server.Now; Server.PacketSent.IP = ClientConn.ClientSocket.LocalEndPoint.ToString(); Server.PacketSent.sender = Server.ServerName; // Checking if the user is already in another chat room. foreach (UserInfo user in Server.ServerUserList) { if (Server.PacketReceived.content == user.UserName) { if (user.CurrentChatRoom != Server.MainHall) { // Finishing packet. Server.PacketSent.title = MsgTitle.add_user_fail.ToString(); Server.PacketSent.content = "Failed to add " + user.UserName + "\nUser already in another room."; ClientConn.sendMsg(Server.PacketSent); } else { // Finishing packet. Server.PacketSent.title = MsgTitle.add_user_success.ToString(); Server.PacketSent.content = "Added " + user.UserName + " to chat room"; // Send packet to each user in chat room, informing a new user added. foreach (UserInfo u in ClientConn.ThisUser.CurrentChatRoom.UserList) { u.ClientConnection.sendMsg(Server.PacketSent); } // Update information for the added user. user.CurrentChatRoom = ClientConn.ThisUser.CurrentChatRoom; ClientConn.ThisUser.CurrentChatRoom.AddUser(user); Server.MainHall.RemoveUser(user); } } } if (Server.PeerServerDict.Count != 0) { // Preparing packet to send to other servers. Server.PacketSent.title = MsgTitle.client_to_chatroom.ToString(); Server.PacketSent.content = ClientConn.ThisUser.CurrentChatRoom.RoomName + " " + Server.PacketReceived.content; foreach (var entry in Server.PeerServerDict.Values) { Server.PacketSent.IP = entry.ClientSocket.LocalEndPoint.ToString(); entry.sendMsg(Server.PacketSent); } } }
public bool _bLoginSuccess; //Were we able to successfully login? /// <summary> /// Constructor /// </summary> public InfClient() { _conn = new ClientConn <InfClient>(new S2CPacketFactory <InfClient>(), this); _syncStart = new ManualResetEvent(false); //Log packets for now.. _conn._bLogPackets = false; _logger = Log.createClient("Client"); _conn._logger = _logger; Client.connectionTimeout = 2000; }
public void NewConnection() { Debugger.Break(); while (true) { ClientConn Client = new ClientConn(); Client.TClient = server.AcceptTcpClient(); NetworkStream stream = Client.TClient.GetStream(); data = new Byte[256]; String MSG = String.Empty; Int32 bytes = stream.Read(data, 0, data.Length); Client.ClientUserName = Encoding.ASCII.GetString(data, 0, bytes); stream.Write(data, 0, bytes); ClientList.Add(Client); } }
// Method: Exit room. public override void Serve() { // Preparing packet to be sent. Server.PacketSent.title = MsgTitle.exit_room.ToString(); Server.PacketSent.IP = ClientConn.ClientSocket.LocalEndPoint.ToString(); Server.PacketSent.time = Server.Now; Server.PacketSent.sender = Server.ServerName; // Inform other users in chat room that someone is leaving. foreach (UserInfo user in ClientConn.ThisUser.CurrentChatRoom.UserList) { if (user != ClientConn.ThisUser) { Server.PacketSent.content = ClientConn.ThisUser.UserName + " has left chat room"; user.ClientConnection.sendMsg(Server.PacketSent); } else { Server.PacketSent.content = "Exitted chat room. You are now in " + Server.MainHall.RoomName; ClientConn.sendMsg(Server.PacketSent); } } if (Server.PeerServerDict.Count != 0) { // Preparing packet to send to other servers. Server.PacketSent.title = MsgTitle.client_outof_chatroom.ToString(); Server.PacketSent.content = ClientConn.ThisUser.CurrentChatRoom.RoomName + " " + ClientConn.ThisUser.UserName; foreach (var entry in Server.PeerServerDict.Values) { Server.PacketSent.IP = entry.ClientSocket.LocalEndPoint.ToString(); entry.sendMsg(Server.PacketSent); } } // Remove user's current room. ClientConn.ThisUser.CurrentChatRoom.RemoveUser(ClientConn.ThisUser); // Put user in main hall. ClientConn.ThisUser.CurrentChatRoom = Server.MainHall; // Add user to main hall list of client. Server.MainHall.AddUser(ClientConn.ThisUser); }
// Method: Create new chat room. public override void Serve() { // Create new local chat room, assign room name, add owner of chat room. string chatRoomName = "S1R" + ChatRoomCount.ToString(); ChatRoomCount++; LocalChatRoom newChatRoom = new LocalChatRoom(Server, chatRoomName, ClientConn.ThisUser); // Update chat room list. Server.LocalChatRoom.Add(newChatRoom); // Update user's current chat room. ClientConn.ThisUser.CurrentChatRoom = newChatRoom; // Remove user from main hall. Server.MainHall.RemoveUser(ClientConn.ThisUser); Console.WriteLine("Update chat room list: " + Server.LocalChatRoom.ToString()); // Preparing the packet to echo back to client. Server.PacketSent.title = MsgTitle.confirm_created.ToString(); Server.PacketSent.time = Server.Now; Server.PacketSent.content = "created " + newChatRoom.RoomName + " you can start chatting now"; Server.PacketSent.IP = ClientConn.ClientSocket.LocalEndPoint.ToString(); Server.PacketSent.sender = Server.ServerName; // Sending packet. ClientConn.sendMsg(Server.PacketSent); if (Server.PeerServerDict.Count != 0) { // Preparing packet to send to other servers. Server.PacketSent.title = MsgTitle.add_chatroom.ToString(); Server.PacketSent.content = chatRoomName; foreach (var entry in Server.PeerServerDict.Values) { Server.PacketSent.IP = entry.ClientSocket.LocalEndPoint.ToString(); entry.sendMsg(Server.PacketSent); } } }
public CfgInfo _zoneConfig; //The zone-specific configuration file public GameClient(Windows.Game wGame, string alias, string ticketid) { _wGame = wGame; _conn = new ClientConn <GameClient>(new S2CPacketFactory <GameClient>(), this); _syncStart = new ManualResetEvent(false); _player = new Player(true); _player._gameclient = this; _player._ticketid = ticketid; _player._alias = alias; //Log packets for now.. _conn._bLogPackets = true; _logger = InfServer.Log.createClient("Client"); _conn._logger = _logger; Client.connectionTimeout = 2000; //Initialize our command registrar _commandRegistrar = new FreeInfantryClient.Game.Commands.Registrar(); _commandRegistrar.register(); }
// Method: Exchanging messages between clients in the same room. public override void Serve() { // Preparing packet to be sent. Server.PacketSent.time = Server.Now; Server.PacketSent.IP = ClientConn.ClientSocket.LocalEndPoint.ToString(); Server.PacketSent.time = MsgTitle.chat_message.ToString(); Server.PacketSent.sender = ClientConn.ThisUser.UserName; // Loop through list of client in current chat room and // send message to all of them. foreach (UserInfo user in ClientConn.ThisUser.CurrentChatRoom.UserList) { if (user != ClientConn.ThisUser) { Server.PacketSent.content = ClientConn.ThisUser.UserName + ": " + Server.PacketReceived.content; user.ClientConnection.sendMsg(Server.PacketSent); } else { Server.PacketSent.content = "You: " + Server.PacketReceived.content; ClientConn.sendMsg(Server.PacketSent); } } }
public override void Serve() { // "client" is the user to request to join chat room // that has "requestUser". UserInfo requestUser = null; foreach (UserInfo user in Server.ServerUserList) { if (user.UserName.Equals(Server.PacketReceived.content)) { requestUser = user; break; } } if (requestUser != null) { if (requestUser.CurrentChatRoom != Server.MainHall) { // Remove user from main hall. Server.MainHall.RemoveUser(ClientConn.ThisUser); // Adding user to the room. requestUser.CurrentChatRoom.AddUser(ClientConn.ThisUser); // Updating user's current room. ClientConn.ThisUser.CurrentChatRoom = requestUser.CurrentChatRoom; // Preparing packet to be sent. Server.PacketSent.content = "Joined " + requestUser.CurrentChatRoom.RoomName + ". You can start sending message now"; Server.PacketSent.title = MsgTitle.confirm_joined.ToString(); Server.PacketSent.sender = Server.ServerName; ClientConn.sendMsg(Server.PacketSent); } else { // Preparing packet to be sent. Server.PacketSent.content = "You both are in main hall"; Server.PacketSent.title = MsgTitle.confirm_joined.ToString(); Server.PacketSent.sender = Server.ServerName; ClientConn.sendMsg(Server.PacketSent); Console.WriteLine("Both users are in main hall"); } if (Server.PeerServerDict.Count != 0) { // Preparing packet to send to other servers. Server.PacketSent.title = MsgTitle.client_to_chatroom.ToString(); Server.PacketSent.content = ClientConn.ThisUser.CurrentChatRoom.RoomName + " " + ClientConn.ThisUser.UserName; foreach (var entry in Server.PeerServerDict.Values) { Server.PacketSent.IP = entry.ClientSocket.LocalEndPoint.ToString(); entry.sendMsg(Server.PacketSent); } } } else { Console.WriteLine("Requested user " + Server.PacketReceived.content + " is not connected to this server."); // Preparing packet to be sent. Server.PacketSent.content = Server.PacketReceived.content; Server.PacketSent.title = MsgTitle.change_server.ToString(); Server.PacketSent.sender = Server.ServerName; ClientConn.sendMsg(Server.PacketSent); Server.FinishedChatting = true; } }
static void Main(string[] args) { //!!删除指定目录下的所有的txt文件日志文件 WriteLog.DeleteLog(); //! 1.根据命令行中的值,初始化hook //! 1、解析参数,更新初始值 argsPrase(args); //! 2、初始化数据库链接信息 ClientConn.PraseDataBaseConfig(!HookHelper.method.Equals("wata")); //解析配置文件,并建立数据库连接。 ClientConn.PraseTableTypeConfig(); //解析数据库对应要解析的表类型链接 ClientConn.PraseComputerTableConfig(); //!3、 初始化与数据库相关的hookhelper变量 InitHookHelper(args); //CSVLog string serverIP = Program.GetLocalIP(HookHelper.serachIP); string hostName = Dns.GetHostName(); string path = ConfigurationManager.AppSettings["CSVLogPath"].ToString() + "\\" + hostName.ToString() + "_" + serverIP.ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"; if (HookHelper.useCSVLOG.Equals("true")) { CSVData.CSVInit(path); } //testEXEListening(); try { string[] nodes = new string[] { HookHelper.computerNode }; if (HookHelper.computerNode.ToUpper().Equals("ALLNODE")) { nodes = new string[] { "ComputeNode1", "ComputeNode2", "ComputeNode3", "ComputeNode4", "ComputeNode5", "ComputeNode6", "ComputeNode7", "ComputeNode8", "ComputeNode9", "ComputeNode10", "ComputeNode11" }; } //! 设置计时器,所有节点时间累加值 Stopwatch totalNodeFolderDat = new Stopwatch(); totalNodeFolderDat.Start(); for (int i = 0; i < nodes.Length; ++i) { HookHelper.computerNode = nodes[i]; //! 为了后续计算速度快,提前从数据库中读取unit单元信息和模型路径信息, if (HookHelper.method.Equals("wata")) { ClientConn.PraseGridUnitConfigAllChina(HookHelper.computerNode); } else { ClientConn.PraseGridUnitConfig(); } // 每个省对应一个数据库连接,每个连接里包含了降雨切片目录 Dictionary <string, Dictionary <string, string> > dbValues = ClientConn.m_dbTableTypes; Dictionary <string, Dictionary <string, DataTable> > dbTableConfigs = ClientConn.m_dbTableConfig; if (HookHelper.method == "province") { CalcOneByOne.runBySingleCC(); //执行插入日志 WriteLog.WriteLogMethod(HookHelper.Log, "runByCCFolder"); break; } if (HookHelper.method == "wata") { //WriteUnitInfo.GetAllHsfxUnitTableByWATA(); if (HookHelper.processModel.ToUpper().Equals("NORMAL")) { CalcOneByOneWata.runBySingleCC(); } else { CalcOneByOneWata.runBySingleCCADD(); } //执行插入日志 WriteLog.WriteLogMethod(HookHelper.Log, "runByCCFolder"); } //! 阻塞程序不关闭 Console.WriteLine(string.Format("当前主机节点{0}网格计算调度完成 ", HookHelper.computerNode) + DateTime.Now); //执行插入日志 WriteLog.WriteLogMethod(HookHelper.Log); Console.WriteLine(string.Format("####################################################################") + DateTime.Now); Console.WriteLine(string.Format(" ") + DateTime.Now); Console.WriteLine(string.Format(" ") + DateTime.Now); Console.WriteLine(string.Format("####################################################################") + DateTime.Now); } totalNodeFolderDat.Stop(); TimeSpan totalNodeFolderDatTime = totalNodeFolderDat.Elapsed; Console.WriteLine(string.Format("{0}个节点调度总耗时:{1}秒", nodes.Length, totalNodeFolderDatTime.TotalMilliseconds / 1000)); HookHelper.Log += string.Format("{0}个节点调度总耗时:{1}秒", nodes.Length, totalNodeFolderDatTime.TotalMilliseconds / 1000) + DateTime.Now + ";\r\n"; if (!HookHelper.isCloseCMD) { Console.Read(); } } catch (Exception ex) { Console.WriteLine(ex); //打印日志 string log = HookHelper.Log + ex; WriteLog.WriteLogMethod(log); Environment.Exit(0); //throw; } //CSVLog if (HookHelper.useCSVLOG.Equals("true")) { CSVFile.SaveCSV(CSVData.GetDataTable(), path); } }
static void Main(string[] args) { //!!删除指定目录下的所有的txt文件日志文件 WriteLog.DeleteLog(); //! 1.根据命令行中的值,初始化hook //! 1、解析参数,更新初始值 argsPrase(args); //! 2、初始化数据库链接信息 ClientConn.PraseDataBaseConfig(!HookHelper.method.Equals("wata")); //解析配置文件,并建立数据库连接。 ClientConn.PraseTableTypeConfig(); //解析数据库对应要解析的表类型链接 ClientConn.PraseComputerTableConfig(); //!3、 初始化与数据库相关的hookhelper变量 InitHookHelper(args); //CSVLog string serverIP = Program.GetLocalIP(HookHelper.serachIP); string hostName = Dns.GetHostName(); string path = ConfigurationManager.AppSettings["CSVLogPath"].ToString() + "\\" + hostName.ToString() + "_" + serverIP.ToString() + "_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".csv"; if (HookHelper.useCSVLOG.Equals("true")) { CSVData.CSVInit(path); } //! 为了后续计算速度快,提前从数据库中读取unit单元信息和模型路径信息, if (HookHelper.method.Equals("wata")) { ClientConn.PraseGridUnitConfigAllChina(HookHelper.computerNode); } else { ClientConn.PraseGridUnitConfig(); } // 每个省对应一个数据库连接,每个连接里包含了降雨切片目录 Dictionary <string, Dictionary <string, string> > dbValues = ClientConn.m_dbTableTypes; Dictionary <string, Dictionary <string, DataTable> > dbTableConfigs = ClientConn.m_dbTableConfig; //testEXEListening(); try { if (HookHelper.method == "province") { CalcOneByOne.runBySingleCC(); //执行插入日志 WriteLog.WriteLogMethod(HookHelper.Log, "runByCCFolder"); } if (HookHelper.method == "wata") { WriteUnitInfo.GetAllHsfxUnitTableByWATA(); CalcOneByOneWata.runBySingleCC(); //执行插入日志 WriteLog.WriteLogMethod(HookHelper.Log, "runByCCFolder"); } //! 阻塞程序不关闭 Console.WriteLine(string.Format("当前主机节点{0}网格计算调度完成 ", HookHelper.computerNode) + DateTime.Now); //执行插入日志 WriteLog.WriteLogMethod(HookHelper.Log); if (!HookHelper.isCloseCMD) { Console.Read(); } } catch (Exception ex) { Console.WriteLine(ex); //打印日志 string log = HookHelper.Log + ex; WriteLog.WriteLogMethod(log); Environment.Exit(0); //throw; } //CSVLog if (HookHelper.useCSVLOG.Equals("true")) { CSVFile.SaveCSV(CSVData.GetDataTable(), path); } }
// Method: Add an user to a chat room when they request to join. public override void Serve() { // Start preparing common features of packet. Server.PacketSent.time = Server.Now; Server.PacketSent.IP = ClientConn.ClientSocket.LocalEndPoint.ToString(); string chatRoom = null; bool roomAlreadyExisted = false; foreach (ChatRoom room in Server.LocalChatRoom) { // Check if the room requested exists. if (Server.PacketReceived.content.Equals(room.RoomName)) { roomAlreadyExisted = true; // Remove user from main hall. Server.MainHall.RemoveUser(ClientConn.ThisUser); // Adding user to the room. room.AddUser(ClientConn.ThisUser); // Updating user's current room. ClientConn.ThisUser.CurrentChatRoom = room; // Preparing packet to be sent. Server.PacketSent.content = "Joined " + room.RoomName + ". You can start sending message now"; Server.PacketSent.title = MsgTitle.confirm_joined.ToString(); Server.PacketSent.sender = Server.ServerName; chatRoom = room.RoomName; break; } } // If room does not exist if (!roomAlreadyExisted) { // Create new room and assign name. string roomName = "S1R" + ChatRoomCount.ToString(); LocalChatRoom newChatRoom = new LocalChatRoom(Server, roomName, ClientConn.ThisUser); // Add chat room to server's list of chat room. Server.LocalChatRoom.Add(newChatRoom); // Remove user from main hall. Server.MainHall.RemoveUser(ClientConn.ThisUser); // Adding user to newly created room. newChatRoom.AddUser(ClientConn.ThisUser); // Updating user's current room. ClientConn.ThisUser.CurrentChatRoom = newChatRoom; // Preparing packet to be sent. Server.PacketSent.content = "Room does not exist. Created a new room: " + roomName; Server.PacketSent.title = MsgTitle.confirm_created.ToString(); Server.PacketSent.sender = Server.ServerName; chatRoom = roomName; } ClientConn.sendMsg(Server.PacketSent); if (Server.PeerServerDict.Count != 0) { // Preparing packet to send to other servers. Server.PacketSent.title = MsgTitle.client_to_chatroom.ToString(); Server.PacketSent.content = chatRoom + " " + ClientConn.ThisUser.UserName; foreach (var entry in Server.PeerServerDict.Values) { Server.PacketSent.IP = entry.ClientSocket.LocalEndPoint.ToString(); entry.sendMsg(Server.PacketSent); } } }
public static bool runBySingleCC() { //!! 场次信息回传 // 更新execpath的值 string start = "2000-01-01T00:00"; string end = "2000-01-01T08:00"; string datnums = "95"; string yearmmddForID = "2000010100"; //! 遍历指定目录下的降雨数据 //! 设置计时器,当前场次时间 Stopwatch totalFolderDat = new Stopwatch(); totalFolderDat.Start(); if (!Directory.Exists(HookHelper.rainSRCDirectory)) { Console.WriteLine(string.Format("{0}台风场dat降雨目录不存在 ", HookHelper.rainSRCDirectory) + DateTime.Now); return(false); } FileInfo[] fInfo = GenRainTileByCSharp.GetRaindatList(); int datnum = fInfo.Length; for (int d = 0; d < datnum; ++d) { int perGroupCount = 0; int perWaitCount = 0; //每次计算当前台风前先删除当前节点下,所有单元的公共传递文件inputq.csv\rainfile.txt //! 当前dat文件全路径 //! 设置计时器,当前场次时间 Stopwatch oneDat = new Stopwatch(); oneDat.Start(); string curDatFullname = fInfo[d].FullName; Console.WriteLine(string.Format("****************************降雨目录下第{0}场*********A************", d + 1) + DateTime.Now); Console.WriteLine(string.Format("*****************************************************AAA***********") + DateTime.Now); Console.WriteLine(string.Format("*****************************{0}场次Start***********AAAAA**********", curDatFullname) + DateTime.Now); Console.WriteLine(string.Format("***************************************************AAAAAAA*********") + DateTime.Now); Console.WriteLine(string.Format("**************************************************AAAAAAAAA********") + DateTime.Now); //! 遍历每个流域的网格模型 //!执行python切片 //!1、执行切片,调用python执行 if (HookHelper.isgenraintile) { //CSVLog //CSVData.addRow(); //! 设置计时器,当前场次时间 Stopwatch perChangci = new Stopwatch(); perChangci.Start(); bool isGenTilesucess = false; if (HookHelper.tilemehtod.ToUpper().Trim().Equals("ALL")) { isGenTilesucess = GenRainTileByCSharp.CreateTileByWATAByCSharp(curDatFullname, ref start, ref end, ref datnums, ref yearmmddForID); } else { isGenTilesucess = GenRainTileByCSharp.CreateTileByWATAByCSharpOneTimeByOne(curDatFullname, ref start, ref end, ref datnums, ref yearmmddForID); } perChangci.Stop(); TimeSpan perChangciTime = perChangci.Elapsed; if (!isGenTilesucess) { //Console.WriteLine(string.Format("{0}区域降雨切片执行失败 ", HookHelper.computerNode) + DateTime.Now); HookHelper.Log += string.Format("{0}区域降雨切片执行失败 ", HookHelper.computerNode) + DateTime.Now + ";\r\n"; continue; } else { Console.WriteLine(string.Format("网格{0}场次降雨切片执行耗时:{1}秒", curDatFullname, perChangciTime.TotalMilliseconds / 1000)); HookHelper.Log += string.Format("网格{0}场次降雨切片执行耗时:{1}秒", curDatFullname, perChangciTime.TotalMilliseconds / 1000) + DateTime.Now + ";\r\n"; Console.WriteLine(string.Format("{0}区域降雨切片执行成功 ", HookHelper.computerNode) + DateTime.Now); //CSVLog if (HookHelper.useCSVLOG.Equals("true")) { CSVData.addData(CSVData.GetRowNumber(), "切片时长", perChangciTime.TotalMilliseconds / 1000); } } } //! 启动bat前每场的时间不同,要更新写出execsingle.bat if (dbTableConfigs["china"].Count > 0) { int appnum = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows.Count; int appValidCount = 0; for (int a = 0; a < appnum; ++a) { //!当前路径 string apppath = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows[a]["AppPath"].ToString(); string ComputeUnit = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows[a]["ComputeUnit"].ToString(); string provinceName = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows[a]["province"].ToString(); //execbat路径 string execpath = apppath + "execsingle.bat"; if (apppath.EndsWith("/")) { execpath = apppath + "execsingle.bat"; } else { execpath = apppath + "\\" + "execsingle.bat"; } if (!dbValues.ContainsKey(provinceName)) { continue; } string outrainTilepath = dbValues[provinceName]["rainTileFolder"]; // 更新execpath的值 bool isUpExec = false; //!覆盖更新通过指定参数到execsingle.bat文件 string datPureName = System.IO.Path.GetFileNameWithoutExtension(curDatFullname); isUpExec = WriteExecBatFile.UpdateExecBatFileByTemplateExecsingle(execpath, ComputeUnit, start, end, datnums, datPureName, outrainTilepath, yearmmddForID); if (isUpExec) { appValidCount++; //Console.WriteLine(string.Format("{0}区域{1}文件execsingle.bat更新成功 ", "china", apppath) + DateTime.Now); } else { //Console.WriteLine(string.Format("{0}区域{1}文件execsingle.bat更新失败 ", "china", apppath) + DateTime.Now); } } Console.WriteLine(string.Format("{0}区域{1}个有效单元的execsingle.bat更新成功 ", "china", appValidCount) + DateTime.Now); //!判断appnum 是否超过了processnum,是则部分启动,等待 //!先根据个数分组,分组后,则循环,则可以等待了 int processGroup = (int)Math.Ceiling((float)appnum / (float)HookHelper.processnum); for (int g = 0; g < processGroup; ++g) { //!循环每个组,pid存在,则执行等待 perGroupCount = 0; while (pids.Count > 0) { //! 执行等待,然后查询更新pids列表.等待1分钟 Console.WriteLine(string.Format("共{0}个分组", processGroup) + DateTime.Now); Console.WriteLine(string.Format("等待第{0}场{1}文件的第{2}进程组计算完成并关闭,pid进程查询更新等待中,等待时长15秒...", d + 1, curDatFullname, g) + DateTime.Now); System.Threading.Thread.Sleep(1000 * 15 * 1); //kill perGroupCount++; Console.WriteLine(string.Format("第{0}进程组,已经等待次数{1}次", g, perGroupCount) + DateTime.Now); if (perGroupCount >= HookHelper.waitcount) { //遍历强制关闭当前场次的所有pid程序 foreach (var item in pids.ToList()) { int curPID = item.Key; Process curProcss = null; try { curProcss = Process.GetProcessById(curPID); } catch (Exception ex) { curProcss = null; } bool isInProcess = curProcss == null ? false : true; if (isInProcess) { //curProcss.Kill(); //HookHelper.Log += string.Format("***********关闭进程开始 ") + DateTime.Now + ";\r\n"; //Console.WriteLine(string.Format("***********关闭进程开始") + DateTime.Now); HookHelper.KillProcessAndChildren(curPID); //Console.WriteLine(string.Format("***********关闭进程结束") + DateTime.Now); //HookHelper.Log += string.Format("***********关闭进程结束 ") + DateTime.Now + ";\r\n"; //写出信息到数据库表中 string datPureNameInsert = System.IO.Path.GetFileNameWithoutExtension(curDatFullname); String inValues = String.Format("('{0}','{1}','{2}','{3}','{4}')", datPureNameInsert, "", item.Value + "-GridControlError", HookHelper.computerNode, HookHelper.localIP); String sqlinserBaseInfo = String.Format("insert into Grid_TaiFeng_ErrorCALC (DATName, AppPath, unitcd, computernode, computerIP) VALUES {0}", inValues); bool isExist = ClientConn.IsValidDat(datPureNameInsert); //错误信息只写出一次 if (isExist) { string keyString = "china"; Dal_Rain.ExecuteSqlInserting(keyString, sqlinserBaseInfo); } } else { Console.WriteLine(string.Format("***********当前进程已自动中止") + DateTime.Now); HookHelper.Log += string.Format("***********当前进程已自动中止") + DateTime.Now + ";\r\n"; } } } //! 遍历pids,查询windows process中是否存在这个pid,不存在,则移除 int pidnum = pids.Count; foreach (var item in pids.ToList()) { int curPID = item.Key; Process curProcss = null; try { curProcss = Process.GetProcessById(curPID); } catch (Exception ex) { curProcss = null; } bool isInProcess = curProcss == null ? false : true; if (!isInProcess) { pids.Remove(item.Key); } else { Console.WriteLine(string.Format("单元{0}所在分组{1}计算进行中......需继续等待......", item.Value, g) + DateTime.Now); } } if (pids.Count == 0) { break; } } //当前分组的起始值,和end值 int startPROCESS = g * HookHelper.processnum; int endPROCESS = (g + 1) * HookHelper.processnum; if (g == processGroup - 1) { endPROCESS = appnum; } int validStartUnitModel = 0; for (int a = startPROCESS; a < endPROCESS; ++a) { //!当前路径 string apppath = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows[a]["AppPath"].ToString(); string ComputeUnit = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows[a]["ComputeUnit"].ToString(); string ComputeNode = dbTableConfigs["china"]["HSFX_ComputeUnit"].Rows[a]["ComputeNode"].ToString(); //execbat路径 string execpath = apppath + "execsingle.bat"; if (apppath.EndsWith("/")) { execpath = apppath + "execsingle.bat"; } else { execpath = apppath + "\\" + "execsingle.bat"; } //! 启动该exec.bat //! 单元信息 string appunitInfo = ComputeNode + "_" + ComputeUnit + "_" + apppath; //启动前判断如果已经存在错误,则跳过不启动 string datPureNameInsertForStart = System.IO.Path.GetFileNameWithoutExtension(curDatFullname); bool isExistForStart = ClientConn.IsValidDat(datPureNameInsertForStart); if (isExistForStart) { bool isOneStart = StartOneByOneExecsingle(execpath, appunitInfo); if (isOneStart) { validStartUnitModel++; HookHelper.Log += string.Format("{0}节点{1}单元{2}路径执行成功 ", HookHelper.computerNode, ComputeUnit, execpath) + DateTime.Now + ";\r\n"; //Console.WriteLine(string.Format("{0}节点{1}单元{2}路径执行成功 ", HookHelper.computerNode, ComputeUnit, execpath) + DateTime.Now); } else { HookHelper.Log += string.Format("{0}节点{1}单元{2}路径执行失败 ", HookHelper.computerNode, ComputeUnit, execpath) + DateTime.Now + ";\r\n"; //Console.WriteLine(string.Format("{0}节点{1}单元{2}路径执行失败 ", HookHelper.computerNode, ComputeUnit, execpath) + DateTime.Now); } } else { Console.WriteLine(appunitInfo + String.Format("单元dem网格场次数据存在异常,台风{0}所在进程跳过启动 ", curDatFullname) + DateTime.Now); HookHelper.Log += appunitInfo + String.Format("单元dem网格场次数据存在异常,台风{0}所在进程跳过启动 ", curDatFullname) + DateTime.Now + ";\r\n"; } } Console.WriteLine(string.Format("{0}节点{1}个有效单元启动命令执行成功 ", HookHelper.computerNode, validStartUnitModel) + DateTime.Now); } } //!上边已经判断了循环里的组,这里需要判断最后一个组,pid存在,则执行等待,直至继续运行到下一步,代表一个场次计算结束 perWaitCount = 0; //如果等待超过1个小时,仍然无法计算,则跳过这个场次,并写出到log中 while (pids.Count > 0) { //! 执行等待,然后查询更新pids列表.等待1分钟 Console.WriteLine(string.Format("等待第{0}场{1}文件计算完成并关闭,pid进程查询更新等待中,等待时长15秒...", d + 1, curDatFullname) + DateTime.Now); System.Threading.Thread.Sleep(1000 * 15 * 1); perWaitCount++; Console.WriteLine(string.Format("最后进程组,已经等待次数{0}次", perWaitCount) + DateTime.Now); if (perWaitCount >= HookHelper.waitcount) { //遍历强制关闭当前场次的所有pid程序 //将该场次值写出到log文件中 string ignoreCCName = curDatFullname; WriteLog.AppendLogMethod(ignoreCCName, "datIgnore"); foreach (var item in pids.ToList()) { int curPID = item.Key; Process curProcss = null; try { curProcss = Process.GetProcessById(curPID); } catch (Exception ex) { curProcss = null; } bool isInProcess = curProcss == null ? false : true; if (isInProcess) { //curProcss.Kill(); //Console.WriteLine(string.Format("***********关闭进程开始") + DateTime.Now); HookHelper.KillProcessAndChildren(curPID); //Console.WriteLine(string.Format("***********关闭进程结束") + DateTime.Now); //写出错误信息到sql中 //当前单元没有正常计算,台风id写出到数据库表中 string datPureNameInsert = System.IO.Path.GetFileNameWithoutExtension(curDatFullname); String inValues = String.Format("('{0}','{1}','{2}','{3}','{4}')", datPureNameInsert, "", item.Value + "-GridControlError", HookHelper.computerNode, HookHelper.localIP); String sqlinserBaseInfo = String.Format("insert into Grid_TaiFeng_ErrorCALC (DATName, AppPath, unitcd, computernode, computerIP) VALUES {0}", inValues); bool isExist = ClientConn.IsValidDat(datPureNameInsert); //错误信息只写出一次 if (isExist) { string keyString = "china"; Dal_Rain.ExecuteSqlInserting(keyString, sqlinserBaseInfo); } } else { Console.WriteLine(string.Format("***********当前进程已自动中止") + DateTime.Now); HookHelper.Log += string.Format("***********当前进程已自动中止") + DateTime.Now + ";\r\n"; } } } //! 遍历pids,查询windows process中是否存在这个pid,不存在,则移除 int pidnum = pids.Count; foreach (var item in pids.ToList()) { int curPID = item.Key; Process curProcss = null; try { curProcss = Process.GetProcessById(curPID); } catch (Exception ex) { curProcss = null; } bool isInProcess = curProcss == null ? false : true; if (!isInProcess) { pids.Remove(item.Key); } else { Console.WriteLine(string.Format("最后一组单元{0}计算进行中......需继续等待......", item.Value) + DateTime.Now); } } if (pids.Count == 0) { break; } } Console.WriteLine(string.Format("{0}台风场所有流域计算完成 ", curDatFullname) + DateTime.Now); HookHelper.Log += string.Format("{0}台风场所有流域计算完成 ", curDatFullname) + DateTime.Now + ";\r\n"; Console.WriteLine(string.Format("******************************************************A************") + DateTime.Now); Console.WriteLine(string.Format("*****************************************************AAA***********") + DateTime.Now); Console.WriteLine(string.Format("*****************************{0}场次END*************AAAAA**********", curDatFullname) + DateTime.Now); Console.WriteLine(string.Format("***************************************************AAAAAAA*********") + DateTime.Now); Console.WriteLine(string.Format("**************************************************AAAAAAAAA********") + DateTime.Now); Console.WriteLine(string.Format("****************************降雨目录下第{0}场结束******************", d + 1) + DateTime.Now); oneDat.Stop(); TimeSpan oneDatTime = oneDat.Elapsed; Console.WriteLine(string.Format("网格{0}场次降雨切片->bat信息更新->等待网格流域计算,单场次全流程耗时:{1}秒", curDatFullname, oneDatTime.TotalMilliseconds / 1000)); HookHelper.Log += string.Format("网格{0}场次降雨切片->bat信息更新->等待网格流域计算,单场次全流程耗时:{1}秒", curDatFullname, oneDatTime.TotalMilliseconds / 1000) + DateTime.Now + ";\r\n"; Console.WriteLine(string.Format("####################################################################") + DateTime.Now); Console.WriteLine(string.Format(" ") + DateTime.Now); Console.WriteLine(string.Format(" ") + DateTime.Now); Console.WriteLine(string.Format("####################################################################") + DateTime.Now); //CSVLog if (HookHelper.useCSVLOG.Equals("true")) { CSVData.addData(CSVData.GetRowNumber(), "单场台风时长", oneDatTime.TotalMilliseconds / 1000); CSVData.addData(CSVData.GetRowNumber(), "单场计算时长", oneDatTime.TotalMilliseconds / 1000 - (double)CSVData.LogDataTable.Rows[CSVData.GetRowNumber()]["切片时长"]); } } Console.WriteLine(string.Format("{0}场台风场次逐场次流域计算完成 ", datnum) + DateTime.Now); HookHelper.Log += string.Format("{0}场台风场次逐场次流域计算完成 ", datnum) + DateTime.Now + ";\r\n"; Console.WriteLine(string.Format("*********(-_-) **************{0}场台风场次逐场次流域计算完成*******..~^_^~..***********", datnum) + DateTime.Now); Console.WriteLine(string.Format("*********(-_-) ***************{0}场台风场次逐场次流域计算完成*******..~^_^~..**********", datnum) + DateTime.Now); Console.WriteLine(string.Format("*********(-_-) ***************{0}场台风场次逐场次流域计算完成*******..~^_^~..**********", datnum) + DateTime.Now); Console.WriteLine(string.Format("********(-_-) **************{0}场台风场次逐场次流域计算完成*******..~^_^~..**********", datnum) + DateTime.Now); Console.WriteLine(string.Format("********(-_-) ***************{0}场台风场次逐场次流域计算完成*******..~^_^~..*********", datnum) + DateTime.Now); Console.WriteLine(string.Format("********(-_-) ****************{0}场台风场次逐场次流域计算完成*******..~^_^~..**********", datnum) + DateTime.Now); totalFolderDat.Stop(); TimeSpan totalFolderDatTime = totalFolderDat.Elapsed; Console.WriteLine(string.Format("{0}降雨目录下{1}个降雨文件从降雨切片->bat信息更新->等待网格流域计算,总耗时:{2}秒", HookHelper.rainSRCDirectory, datnum, totalFolderDatTime.TotalMilliseconds / 1000)); HookHelper.Log += string.Format("{0}降雨目录下{1}个降雨文件从降雨切片->bat信息更新->等待网格流域计算,总耗时:{2}秒", HookHelper.rainSRCDirectory, datnum, totalFolderDatTime.TotalMilliseconds / 1000) + DateTime.Now + ";\r\n"; return(true); }