一个使用C#和ArcPy实现的版本压缩工具(五)
目录
ArcGIS版本压缩功能设计与开发
目录
ArcGIS版本压缩功能设计与开发
服务器端接收命令进行压缩(Socket通讯)
public class SocketService
{
//和客户端连接的套接字
static Socket socketListener = null;
//用于暂存客户端连接信息的套接字集合
static Dictionary<string, Socket> dictSocketClients = new Dictionary<string, Socket>() { };
/// <summary>
/// 启动监听的入口函数
/// </summary>
public static void Start()
{
try
{
//监听器,用于监听客户端发来的消息(IPv4寻址,流式连接,TCP协议)
socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//获取配置中的IP和端口
var sIP = CompressionParameter.m_dictConfig[CompressionParameter.m_sServerIP];
var nPort = int.Parse(CompressionParameter.m_dictConfig[CompressionParameter.m_sServerPort]);
//重新保存IP和端口到配置文件中
CompressionParameter.m_configManager.SaveAppSetting(CompressionParameter.m_sServerIP, sIP);
CompressionParameter.m_configManager.SaveAppSetting(CompressionParameter.m_sServerPort, nPort.ToString());
//监听对象绑定IP地址与端口设置
IPAddress ipAddress = IPAddress.Parse(sIP);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, nPort);
socketListener.Bind(ipEndPoint);
//排队长度
socketListener.Listen(8);
//创建一个监听线程
new Thread(ListenForConnectionRequests) { IsBackground = true }.Start();
Log.Loging.Info($"Listener On {sIP}:{nPort}");
}
catch (Exception ex)
{
Log.Loging.Error($"Exception: {ex.Message}");
}
}
/// <summary>
/// 监听客户端发来连接请求
/// </summary>
private static void ListenForConnectionRequests()
{
//负责连接的套接字对象
Socket socketConnector = null;
while (true)
{
try
{
socketConnector = socketListener.Accept();
}
catch (Exception e)
{
Log.Loging.Error(e.Message);
break;
}
//获取客户端的IP和端口号
IPEndPoint ipEndPoint = socketConnector.RemoteEndPoint as IPEndPoint;
IPAddress ipAddress = ipEndPoint.Address;
int nPort = ipEndPoint.Port;
//将客户端连接成功的消息返回给客户端
var sConnectionInfo = $"Connect Successfully! Your IP: {ipAddress}, Your Port: {nPort}";
socketConnector.Send(ResponseOkToBuffer(sConnectionInfo));
//保存客户端连接信息
var sClientInfo = socketConnector.RemoteEndPoint.ToString();
Log.Loging.Info($"Client [{sClientInfo}] Connected");
dictSocketClients.Add(sClientInfo, socketConnector);
//创建一个通信线程,接收请求
new Thread(new ParameterizedThreadStart(ListenForMessages)) { IsBackground = true }.Start(socketConnector);
}
}
/// <summary>
/// 接收器,用于接收客户端消息
/// </summary>
/// <param name="socketClientInfo"></param>
static void ListenForMessages(object socketClientInfo)
{
//负责通讯的套接字(消息往来负责人,我们将其命名为“出纳员”)
Socket socketTeller = socketClientInfo as Socket;
while (true)
{
//创建一个内存缓冲区,大小为1024*1024字节,即1M
var arrMessage = new byte[1024 * 1024];
//将接收到的信息存入内存缓冲区,并返回其字节数组的长度
try
{
int nLength = socketTeller.Receive(arrMessage);
var sMessage = Encoding.UTF8.GetString(arrMessage, 0, nLength);
Log.Loging.Info($"Server Received a new Message: {sMessage}");
socketTeller.Send(ResponseOkToBuffer($"Server Received Your Message: {sMessage}"));
//出纳负责处理命令并出具回执
ExecuteCommand(sMessage, ref socketTeller);
}
catch (Exception ex)
{
Log.Loging.Error($"Server Exception: {ex.Message}");
var sClient = socketTeller.RemoteEndPoint.ToString();
dictSocketClients.Remove(sClient);
Log.Loging.Info($"Server Removed Client: {sClient}");
Log.Loging.Info($"Server Fired a Teller");
socketTeller.Close();
break;
}
}
}
/// <summary>
/// 执行命令
/// </summary>
/// <param name="sCommand"></param>
/// <param name="socket"></param>
static void ExecuteCommand(string sCommand, ref Socket socket)
{
var sCmd = sCommand.Trim();
var sMessage = "Nothing to do with Whitespace Command.";
if (string.IsNullOrEmpty(sCmd))
{
Log.Loging.Info(sMessage);
}
else
{
if (0 == string.Compare(sCmd, "CompressNormally", StringComparison.OrdinalIgnoreCase))
{
sMessage = "Executed: CompressNormally";
Compression.CompressNormally();
}
else if (0 == string.Compare(sCmd, "CompressAutomatically", StringComparison.OrdinalIgnoreCase))
{
sMessage = "Executed: CompressAutomatically";
Compression.CompressAutomatically();
}
else if (0 == string.Compare(sCmd, "CompressCompletely", StringComparison.OrdinalIgnoreCase))
{
sMessage = "Executed: CompressCompletely";
Compression.CompressCompletely();
}
else
{
sMessage = $"Nothing to do with CommandLine: {sCmd}";
Log.Loging.Info(sMessage);
}
}
socket.Send(ResponseOkToBuffer(sMessage));
}
static byte[] ResponseOkToBuffer(string sMessage)
{
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new ResponseOk() { Description = sMessage }));
}
static byte[] ResponseCommonErrorToBuffer(string sMessage)
{
return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new ResponseCommonError() { Description = sMessage }));
}
}
客户端发送命令执行压缩(Socket通讯)
- 界面
- 代码
public partial class FormSender : Form
{
Thread threadClient = null;
Socket socketClient = null;
IPAddress ipAddress = null;
private delegate void DelegateWriteLine(string sContent);
int nPort = -1;
public FormSender()
{
InitializeComponent();
}
private void TextBoxPort_KeyPress(object sender, KeyPressEventArgs e)
{
if (!(char.IsNumber(e.KeyChar)) && (char)8 != e.KeyChar)
{
e.Handled = true;
}
}
private void ButtonClearParam_Click(object sender, EventArgs e)
{
ipAddressInput1.Value = null;
textBoxPort.Clear();
}
private void ButtonCompressNormally_Click(object sender, EventArgs e)
{
textBoxEditor.Text = "CompressNormally";
}
private void ButtonCompressAutomatically_Click(object sender, EventArgs e)
{
textBoxEditor.Text = "CompressAutomatically";
}
private void ButtonCompressCompletely_Click(object sender, EventArgs e)
{
textBoxEditor.Text = "CompressCompletely";
}
private void ButtonSend_Click(object sender, EventArgs e)
{
try
{
var sContent = textBoxEditor.Text.Trim();
if (string.IsNullOrEmpty(sContent))
{
MessageBox.Show("请先输入要发送的内容!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
byte[] arrMessage = Encoding.UTF8.GetBytes(sContent);
WriteLine($"Client: \r\n{sContent}");
if (null == socketClient)
{
MessageBox.Show("请先连接服务器端,成功后再发送消息!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
socketClient.Send(arrMessage);
}
}
catch(Exception ex)
{
WriteLine($"Exception: {ex.Message}");
}
}
private void ButtonSetParam_Click(object sender, EventArgs e)
{
if (null != threadClient)
{
if (null != socketClient)
{
socketClient.Dispose();
}
threadClient.Abort();
}
socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ipAddress = IPAddress.Parse(ipAddressInput1.Value);
nPort = int.Parse(textBoxPort.Text);
try
{
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, nPort);
socketClient.Connect(ipEndPoint);
}
catch (Exception ex)
{
if (null != socketClient)
{
socketClient.Dispose();
socketClient = null;
}
WriteLine($"Exception. {ex.Message}");
}
threadClient = new Thread(Receiver)
{
IsBackground = true
};
threadClient.Start();
}
private void Receiver()
{
while (true)
{
Application.DoEvents();
try
{
byte[] arrMessage = new byte[1024 * 1024];
int nLength = socketClient.Receive(arrMessage);
string sMessage = Encoding.UTF8.GetString(arrMessage, 0, nLength);
WriteLine($"Server: \r\n{sMessage}");
}
catch (Exception e)
{
WriteLine($"Exception: {e.Message}");
break;
}
}
}
private void WriteLine(string sContent)
{
if (InvokeRequired)
{
var delegateWrite = new DelegateWriteLine(WriteLine);
Invoke(delegateWrite, sContent);
}
else
{
if (textBoxMessage.GetLineFromCharIndex(textBoxMessage.Text.Length) > 100)
textBoxMessage.Clear();
textBoxMessage.AppendText(DateTime.Now.ToString("HH:mm:ss ") + sContent + "\r\n");
textBoxMessage.ScrollToCaret();
}
}
}
转载自:https://blog.csdn.net/a_dev/article/details/88602847