private void runSub() { while(this.mNetwork == null ) { if (this.mHostName == null) { // サーバーになる // 接続があるのを待つ TcpListener listener = new TcpListener(IPAddress.Any, this.mPort); listener.Server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 10000); listener.Start(); while (!this.mStopFlag) { if (listener.Pending()) { // 接続完了 TcpClient client = listener.AcceptTcpClient(); if (client.GetStream() == null) continue; this.mNetwork = new GodaiLibrary.Network(client.GetStream()); break; } else { Thread.Sleep(1000); // 接続待ち } } listener.Stop(); if (this.mStopFlag) { // 中止フラグが立っていたら終了する return; } } else { // クライアントになる // 接続を試みる TcpClient client = new TcpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 10000); client.Connect(this.mHostName, this.mPort); if ( client.GetStream() == null ) continue; this.mNetwork = new GodaiLibrary.Network(client.GetStream()); } } // 監視処理開始 if (this.mWathcer != null) this.mWathcer.Dispose(); this.mWathcer = new FileSystemWatcher(); if (!Directory.Exists(this.mSyncFolder)) Directory.CreateDirectory(this.mSyncFolder); this.mWathcer.Path = this.mSyncFolder; this.mWathcer.NotifyFilter = (NotifyFilters.DirectoryName | NotifyFilters.LastWrite | NotifyFilters.FileName); this.mWathcer.Filter = ""; this.mWathcer.IncludeSubdirectories = true; this.mWathcer.SynchronizingObject = this.mParent; this.mWathcer.Changed += new FileSystemEventHandler(watcher_Changed); this.mWathcer.Created += new FileSystemEventHandler(watcher_Changed); this.mWathcer.Deleted += new FileSystemEventHandler(watcher_Changed); this.mWathcer.Renamed += new RenamedEventHandler(watcher_Renamed); this.mWathcer.EnableRaisingEvents = true; this.mParent.addLog(this.mSyncFolder + "の監視を始めました"); // 送信ループを立ち上げる Thread threadSend = new Thread(new ThreadStart(this.runSend)); threadSend.IsBackground = true; threadSend.Start(); // 受信ループ while (!this.mStopFlag) { int nCom = this.mNetwork.receiveByte(); if (nCom == COM_NO_OP) { continue; } else if (nCom == COM_SENDFILE) { this.mCntNoOp = 0; // ファイルを受信する GodaiLibrary.Network.receiveFiles(this.mNetwork, this.mSyncFolder, this); // 再びONにする // this.mWathcer.EnableRaisingEvents = true; // this.mIgnorePath = null; } else if (nCom == COM_DELETEFILE) { // ファイルを削除する String strPath = this.mNetwork.receiveString(); if (File.Exists(strPath)) { try { File.Delete(strPath); this.mParent.addLog("「" + strPath + "」を削除しました。"); } catch (Exception ex) { } } } } }
public void run() { while (true) { try { runSub(); } catch (Exception ex) { this.mNetwork = null; // MessageBox.Show(ex.Message); } } }