You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

203 lines
4.9 KiB

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
namespace Sog.IO
{
//使用文件的命令处理类,临时使用,这种实现方法效率太低,使用共享内存好得多
public class ShareFileCommand : IShareCommand
{
private uint m_appID;
private string m_filePathName;
const string SHARE_FILE_END_STRING = "SogFileEND";
public void Close()
{
}
public void DeleteFile()
{
if(m_appID == 0)
{
return;
}
if(m_filePathName == null)
{
return;
}
if(File.Exists(m_filePathName))
{
File.Delete(m_filePathName);
}
}
private string GetFilePathName()
{
return "./sog_shf_" + ServerIDUtils.IDToString(m_appID);
}
public ShareFileCommand(uint appID)
{
m_appID = appID;
m_filePathName = GetFilePathName();
}
public void Create()
{
try
{
using (File.Create(m_filePathName))
{
}
}
catch (Exception ex)
{
ex.Source = "";
}
}
public bool Attach()
{
try
{
if(System.IO.File.Exists(m_filePathName) == true)
{
return true;
}
}
catch(Exception ex)
{
//应该是不存在
Console.WriteLine("ShareMemoryCommand.AttachShareMemory failed ,message",ex.Message);
return false;
}
return true;
}
public bool CheckExist()
{
try
{
if (System.IO.File.Exists(m_filePathName) == true)
{
return true;
}
}
catch (Exception ex)
{
ex.Source = "";
//应该是不存在
return false;
}
return true;
}
public bool WriteCommand(string strCommand)
{
//文件不存在,表示游戏进程未正常启动
if(File.Exists(m_filePathName) == false)
{
return false;
}
//尝试5次,有可能失败吗?
for (int i = 0; i < 5; i++)
{
try
{
//Console.WriteLine("ShareMemoryCommand.WriteCommand {0}", strCommand);
FileStream fileStream = File.OpenWrite(m_filePathName);
StreamWriter sw = new StreamWriter(fileStream);
sw.WriteLine(strCommand);
sw.WriteLine(SHARE_FILE_END_STRING);
sw.Flush();
sw.Dispose();
fileStream.Dispose();
return true;
}
catch (Exception ex)
{
//因为是另外一个进程调用的,所以不能用log
Console.WriteLine("ShareFileCommand.WriteCommand error! {0}, try count {1}", ex.Message, i+1);
}
}
return false;
}
//no imp
public bool WriteAck(string strCommand)
{
throw new NotImplementedException("WriteAck no implemented");
}
public string ReadCommand()
{
//文件不存在,表示游戏进程未正常启动
if (File.Exists(m_filePathName) == false)
{
//尝试创建文件
Create();
return null;
}
try
{
string[] allLines = File.ReadAllLines(m_filePathName);
if(allLines == null)
{
return null;
}
if(allLines.Length < 2)
{
return null;
}
if(allLines[1] != SHARE_FILE_END_STRING)
{
TraceLog.Error("ShareFileCommand.ReadCommand end line need is {0}", SHARE_FILE_END_STRING);
return null;
}
ClearCommand();
return allLines[0];
}
catch (Exception ex)
{
TraceLog.Error("ShareFileCommand.ReadCommand error! {0}", ex.Message);
return null;
}
}
public string ReadCommandAck()
{
throw new NotImplementedException("ReadCommandAck no implemented");
}
private void ClearCommand()
{
//清空文件
Create();
}
}
}