public void OnDBTask(MySqlConnection conn, CustomArgs args) { string token = args.GetParam("token") as string; ClientSession session = args.GetParam("session") as ClientSession; DBBase.DBStoredProcedCmd cmd = new DBBase.DBStoredProcedCmd("PRO_CHECK_LOGIN", conn); cmd.AddParamVChar("token", token, token.Length); int bSuc = cmd.Execute(); if (bSuc == 0) { string account = cmd.GetValue(0, "account") as string; int nGold = (int)cmd.GetValue(0, "gold"); ByteBuffer buffer = new ByteBuffer(); buffer.WriteString(account); buffer.WriteInt(nGold); UserUtil.Add(session.uid, session); SocketUtil.SendMessage(session, Protocal.Login, buffer); return; } }
/// <summary> /// sproto消息 /// </summary> void OnSprotoMessage(ClientSession session, ByteBuffer buffer) { byte[] data = buffer.ReadBytes(); //------------------------------------------------------------- SprotoPack spack = new SprotoPack(); byte[] pack_data = spack.pack(data); // pack byte[] unpack_data = spack.unpack(pack_data); // unpack AddressBook addr = new AddressBook(unpack_data); // decode Console.WriteLine("OnSprotoMessage id=>>" + addr.person.Count); buffer.Close(); buffer = null; //------------------------------------------------------------- ByteBuffer newBuffer = new ByteBuffer(); newBuffer.WriteByte((byte)ProtocalType.SPROTO); newBuffer.WriteBytes(data); //添加数据 SocketUtil.SendMessage(session, Protocal.Login, newBuffer); }
private void StartConnect() { try { CreateRemote(); // Setting up proxy EndPoint proxyEP; if (_config.useProxy) { remote = new Socks5Proxy(); proxyEP = SocketUtil.GetEndPoint(_config.proxyServer, _config.proxyPort); } else { remote = new DirectConnect(); proxyEP = null; } ProxyTimer proxyTimer = new ProxyTimer(3000); proxyTimer.AutoReset = false; proxyTimer.Elapsed += proxyConnectTimer_Elapsed; proxyTimer.Enabled = true; proxyTimer.Proxy = remote; proxyTimer.DestEndPoint = SocketUtil.GetEndPoint(server.server, server.server_port); proxyTimer.Server = server; _proxyConnected = false; // Connect to the proxy server. remote.BeginConnectProxy(proxyEP, new AsyncCallback(ProxyConnectCallback), proxyTimer); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void Start(byte[] firstPacket, int length, Socket socket, int targetPort) { this._firstPacket = firstPacket; this._firstPacketLength = length; this._local = socket; try { EndPoint remoteEP = SocketUtil.GetEndPoint("localhost", targetPort); _remote = SocketUtil.CreateSocket(remoteEP); _remote.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); // Connect to the remote endpoint. _remote.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), null); } catch (Exception e) { Logging.LogUsefulException(e); this.Close(); } }
static int _CreateSocketUtil(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 0) { SocketUtil obj = new SocketUtil(); ToLua.PushObject(L, obj); return(1); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to ctor method: SocketUtil.New")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
/// <summary> /// 应用 /// 注意:在预警规则管理界面更改预警参数值时,不会将预警参数值应用至绑定的巷道。 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnApply_Click(object sender, EventArgs e) { if (selectTunnelSimple1.SelectedTunnel != null) { _preWarningRulesPanel.ApplyParamsValues(); if ( !_preWarningRulesPanel.UpdateTunnelBindingRuleCodeAndParamsInfo( selectTunnelSimple1.SelectedTunnel.TunnelId)) { MessageBox.Show(@"更新巷道绑定的规则参数失败!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { Alert.noteMsg("应用成功!"); // TODO, 需要修改日期 //通知服务器预警数据已更新 var msg = new ResetTunnelRulesMsg(Const.INVALID_ID, selectTunnelSimple1.SelectedTunnel.TunnelId, TunnelInfoDbConstNames.TABLE_NAME, DateTime.Now); SocketUtil.SendMsg2Server(msg); } } }
/// <summary> /// 提交地质构造特有信息 /// </summary> /// <returns></returns> private bool SubmitGeologicStructure() { _geologicStructureEntity = _mineDataEntity.changeToGeologicStructureEntity(); _geologicStructureEntity.NoPlanStructure = _geologicStructure.geoligicStructureEntity.NoPlanStructure; _geologicStructureEntity.PassedStructureRuleInvalid = _geologicStructure.geoligicStructureEntity.PassedStructureRuleInvalid; _geologicStructureEntity.YellowRuleInvalid = _geologicStructure.geoligicStructureEntity.YellowRuleInvalid; _geologicStructureEntity.RoofBroken = _geologicStructure.geoligicStructureEntity.RoofBroken; _geologicStructureEntity.CoalSeamSoft = _geologicStructure.geoligicStructureEntity.CoalSeamSoft; _geologicStructureEntity.CoalSeamBranch = _geologicStructure.geoligicStructureEntity.CoalSeamBranch; _geologicStructureEntity.RoofChange = _geologicStructure.geoligicStructureEntity.RoofChange; _geologicStructureEntity.GangueDisappear = _geologicStructure.geoligicStructureEntity.GangueDisappear; _geologicStructureEntity.GangueLocationChange = _geologicStructure.geoligicStructureEntity.GangueLocationChange; bool bResult = false; if (Text == new LibPanels(MineDataPanelName.GeologicStructure).panelFormName) { _geologicStructureEntity.Save(); bResult = true; Log.Debug("发送添加地址构造信息的Socket信息"); var msg = new UpdateWarningDataMsg(Const.INVALID_ID, selectTunnelSimple1.SelectedTunnel.TunnelId, GeologicStructure.TableName, OPERATION_TYPE.ADD, dtpDateTime.Value); SocketUtil.SendMsg2Server(msg); Log.Debug("发送添加地址构造信息的Socket信息完成"); } else if (Text == new LibPanels(MineDataPanelName.GeologicStructure_Change).panelFormName) { _geologicStructureEntity.Save(); bResult = true; Log.Debug("发送修改地址构造信息的Socket信息"); var msg = new UpdateWarningDataMsg(Const.INVALID_ID, selectTunnelSimple1.SelectedTunnel.TunnelId, GeologicStructure.TableName, OPERATION_TYPE.UPDATE, dtpDateTime.Value); SocketUtil.SendMsg2Server(msg); Log.Debug("发送修改地址构造信息的Socket信息完成"); } return(bResult); }
private void MainForm_GM_Load(object sender, EventArgs e) { SocketUtil.DoInitilization(); Log.Debug("[GM]....Ready to load MXD file....."); ///文件菜单 mapControl_GM.LoadMxFile(Application.StartupPath + "\\" + ConfigManager.Instance.getValueByKey(ConfigConst.CONFIG_MXD_FILE)); //this.mapControl_GM.LoadMxFile(Application.StartupPath + "\\local.mxd"); Log.Debug("[GM]....Finished to load MXD file....."); statusStrip1.AxMap = mapControl_GM; m_FileMenu.AxMapControl = mapControl_GM; //传入MapControl控件 ///加载数据 var mapControl = (IMapControl3)mapControl_GM.Object; var toolbarControl = (IToolbarControl)toolBar_GM.Object; //绑定控件 toolBar_GM.SetBuddyControl(mapControl); tocControl_GM.SetBuddyControl(mapControl); //给全局变量赋值 DataEditCommon.g_tbCtlEdit = toolbarControl; DataEditCommon.g_pAxMapControl = mapControl_GM; DataEditCommon.g_axTocControl = tocControl_GM; DataEditCommon.load(); AddToolBar.Addtool(mapControl_GM, mapControl, toolbarControl, DataEditCommon.g_pCurrentWorkSpace); //给GIS工程的全局变量赋值 Global.SetInitialParams(mapControl_GM.ActiveView); Log.Debug("[GM]....Construction finished."); //浮动工具条中文设置 AutoUpdater.Start("http://bltmld.vicp.cc:8090/sys3/update.xml"); DXSeting.floatToolsLoadSet(); Log.Debug("[GM]....Loading finished."); }
/// <summary> /// 删除按钮事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void tsBtnDel_Click(object sender, EventArgs e) { //确认删除 if (!Alert.confirm(Const.DEL_CONFIRM_MSG)) { return; } var entity = (DayReportJj)gridView1.GetFocusedRow(); // 掘进工作面,只有一条巷道 var tunnel = Tunnel.FindFirstByWorkingFaceId(entity.WorkingFace.WorkingFaceId); DelJJCD(tunnel.TunnelId.ToString(CultureInfo.InvariantCulture), entity.BindingId, entity.WorkingFace.WorkingFaceId); entity.Delete(); RefreshData(); // 向server端发送更新预警数据 var msg = new UpdateWarningDataMsg(entity.WorkingFace.WorkingFaceId, Const.INVALID_ID, DayReportJj.TableName, OPERATION_TYPE.DELETE, DateTime.Now); SocketUtil.SendMsg2Server(msg); }
public void RunNextTest(string directory) { CurrentTest = TestQueue.Dequeue(); NetworkStream stream = clientSocket.GetStream(); Console.WriteLine("Running " + CurrentTest.TestName + " ..."); SocketUtil.SendMessage(stream, "start;" + CurrentTest.TestName); SQLResponse response = RunQuerySync(CurrentTest.Query); if (response == null) { Console.WriteLine("Test " + CurrentTest.TestName + " failed :("); SocketUtil.SendMessage(stream, "reset;failed"); } else { Console.WriteLine("Test " + CurrentTest.TestName + " Passed! Execution Time: " + response.ExecutionTime + " ms"); SocketUtil.SendMessage(stream, "reset"); string jsonData = GetOrderedResult(stream); HandleResult(directory, jsonData, response); } }
private void OnFinish(byte[] lastBytes, int index, int length, object state) { if (Closed) { return; } if (_targetHost == null) { Logging.Error("Unknown host"); Close(); } else { if (length > 0) { _lastBytes = lastBytes; _lastBytesIndex = index; _lastBytesLength = length; } StartConnect(SocketUtil.GetEndPoint(_targetHost, _targetPort)); } }
private void ProcessConnect(SocketAsyncEventArgs e) { e.Completed -= OnConnectAsyncCompleted; e.AcceptSocket = null; e.RemoteEndPoint = null; e.Dispose(); if (e.SocketError != SocketError.Success) { SocketUtil.ShutdownSocket(Socket); Log <ClientSocket> .Error(string.Format("Client socket connect failed, name: {0}, remotingServerEndPoint: {1}, socketError: {2}", Name, ServerEndPoint, e.SocketError)); OnConnectionFailed(ServerEndPoint, e.SocketError); _waitConnectHandle.Set(); return; } Connection = new TcpConnection(Name, Socket, Setting, _receivedBufferPool, _sendBufferPool, _tcpConnectionHandler); Connection.RegisterConnectionEventListener(_tcpConnectionEventListeners); LocalEndPoint = Connection.LocalEndPoint; Log <ClientSocket> .Info(string.Format("Client socket connected, name: {0}, remotingServerEndPoint: {1}, localEndPoint: {2}", Name, Connection.RemotingEndPoint, Connection.LocalEndPoint)); OnConnectionEstablished(Connection); }
/// <summary> /// Get the response from server /// </summary> /// <returns></returns> private HandshakeResponse GetHandshakeResponse() { byte[] buffer = new byte[4]; ///First we receive the 4 bytes of data /// SocketUtil.Receive(this._socket, buffer); int incomingLen = AppUtil.FromByteArray(buffer); if (incomingLen <= 0) { throw new Exception("The handshake process with receiver failed. No response from the server received"); } ///Creat a new buffer to receive handshake response bytes buffer = new byte[incomingLen]; SocketUtil.Receive(this._socket, buffer); ///Now we create a binary formatter to deserialize the handshake response /// BinaryFormatter formatter = new BinaryFormatter(); ///Create a stream containing the serialized bytes using (MemoryStream stream = new MemoryStream(buffer)) { ///Deserialize it and try to cast it in HandshakeResponse HandshakeResponse response = formatter.Deserialize(stream) as HandshakeResponse; ///Close the stream stream.Close(); return(response); } }
/// <summary> /// 提交瓦斯特有信息 /// </summary> private bool SubmitG() { _gdEntity = _mineDataEntity.ChangeToGasDataEntity(); _gdEntity.PowerFailure = _gasData.GasDataEntity.PowerFailure; _gdEntity.DrillTimes = _gasData.GasDataEntity.DrillTimes; _gdEntity.GasTimes = _gasData.GasDataEntity.GasTimes; _gdEntity.TempDownTimes = _gasData.GasDataEntity.TempDownTimes; _gdEntity.CoalBangTimes = _gasData.GasDataEntity.CoalBangTimes; _gdEntity.CraterTimes = _gasData.GasDataEntity.CraterTimes; _gdEntity.StoperTimes = _gasData.GasDataEntity.StoperTimes; //瓦斯浓度 _gdEntity.GasThickness = _gasData.GasDataEntity.GasThickness; bool bResult = false; if (Text == new LibPanels(MineDataPanelName.GasData).panelFormName) { _gdEntity.Save(); bResult = true; Log.Debug("发送添加瓦斯信息的Socket信息"); var msg = new UpdateWarningDataMsg(Const.INVALID_ID, selectTunnelSimple1.SelectedTunnel.TunnelId, GasData.TableName, OPERATION_TYPE.ADD, dtpDateTime.Value); SocketUtil.SendMsg2Server(msg); Log.Debug("发送添加瓦斯信息的Socket信息完成"); } else if (Text == new LibPanels(MineDataPanelName.GasData_Change).panelFormName) { Log.Debug("发送修改瓦斯信息的Socket信息"); var msg = new UpdateWarningDataMsg(Const.INVALID_ID, selectTunnelSimple1.SelectedTunnel.TunnelId, GasData.TableName, OPERATION_TYPE.UPDATE, dtpDateTime.Value); SocketUtil.SendMsg2Server(msg); _gdEntity.Save(); bResult = true; Log.Debug("发送修改瓦斯信息的Socket信息完成"); } return(bResult); }
private void MainForm_OP_Load(object sender, EventArgs e) { SocketUtil.DoInitilization(); mapControl_OP.LoadMxFile(Application.StartupPath + "\\" + ConfigManager.Instance.getValueByKey(ConfigConst.CONFIG_MXD_FILE)); statusStrip1.AxMap = mapControl_OP; m_FileMenu.AxMapControl = mapControl_OP; //传入MapControl控件 var mapControl = (IMapControl3)mapControl_OP.Object; var toolbarControl = (IToolbarControl)toolbar_OP.Object; //绑定控件 toolbar_OP.SetBuddyControl(mapControl); tocControl_OP.SetBuddyControl(mapControl); //给全局变量赋值 DataEditCommon.g_tbCtlEdit = toolbarControl; DataEditCommon.g_pAxMapControl = mapControl_OP; DataEditCommon.g_axTocControl = tocControl_OP; DataEditCommon.load(); AddToolBar.Addtool(mapControl_OP, mapControl, toolbarControl, DataEditCommon.g_pCurrentWorkSpace); AutoUpdater.Start("http://bltmld.vicp.cc:8090/sys4/update.xml"); DXSeting.floatToolsLoadSet(); }
private void StartConnect() { try { CreateRemote(); // Setting up proxy IProxy remote; EndPoint proxyEP = null; EndPoint serverEP = SocketUtil.GetEndPoint(_server.server, _server.server_port); EndPoint pluginEP = _controller.GetPluginLocalEndPointIfConfigured(_server); if (pluginEP != null) { serverEP = pluginEP; remote = new DirectConnect(); } else if (_config.proxy.useProxy) { switch (_config.proxy.proxyType) { case ProxyConfig.PROXY_SOCKS5: remote = new Socks5Proxy(); break; case ProxyConfig.PROXY_HTTP: remote = new HttpProxy(); break; default: throw new NotSupportedException("Unknown forward proxy."); } proxyEP = SocketUtil.GetEndPoint(_config.proxy.proxyServer, _config.proxy.proxyPort); } else { remote = new DirectConnect(); } var session = new AsyncSession(remote); lock (_closeConnLock) { if (_closed) { remote.Close(); return; } _currentRemoteSession = session; } ProxyTimer proxyTimer = new ProxyTimer(_proxyTimeout) { AutoReset = false }; proxyTimer.Elapsed += ProxyConnectTimer_Elapsed; proxyTimer.Enabled = true; proxyTimer.Session = session; proxyTimer.DestEndPoint = serverEP; proxyTimer.Server = _server; _proxyConnected = false; // Connect to the proxy server. remote.BeginConnectProxy(proxyEP, ProxyConnectCallback, new AsyncSession <ProxyTimer>(remote, proxyTimer)); } catch (Exception e) { Logger.LogUsefulException(e); Close(); } }
private void OnAddressFullyRead(IAsyncResult ar) { if (_closed) { return; } try { int bytesRead = _connection.EndReceive(ar); var states = (object[])ar.AsyncState; int bytesRemain = (int)states[0]; var onSuccess = (Action)states[1]; if (bytesRead >= bytesRemain) { _firstPacketLength = bytesRead + 2; int atyp = _connetionRecvBuffer[0]; string dstAddr = "Unknown"; int dstPort = -1; switch (atyp) { case ATYP_IPv4: // IPv4 address, 4 bytes dstAddr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString(); dstPort = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6]; _addrBufLength = ADDR_ATYP_LEN + 4 + ADDR_PORT_LEN; break; case ATYP_DOMAIN: // domain name, length + str int len = _connetionRecvBuffer[1]; dstAddr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len); dstPort = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3]; _addrBufLength = ADDR_ATYP_LEN + 1 + len + ADDR_PORT_LEN; break; case ATYP_IPv6: // IPv6 address, 16 bytes dstAddr = $"[{new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray())}]"; dstPort = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18]; _addrBufLength = ADDR_ATYP_LEN + 16 + ADDR_PORT_LEN; break; } Logger.Debug($"connect to {dstAddr}:{dstPort}"); _destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort); onSuccess.Invoke(); /* StartConnect() */ } else { Logger.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()"); Close(); } } catch (Exception e) { Logger.LogUsefulException(e); Close(); } }
public void EndConnectDest(IAsyncResult asyncResult) { _remote = SocketUtil.EndConnectTcp(asyncResult); }
public void BeginConnectDest(EndPoint destEndPoint, AsyncCallback callback, object state) { DestEndPoint = destEndPoint; SocketUtil.BeginConnectTcp(destEndPoint, callback, state); }
/// <summary> /// 提交 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSubmit_Click(object sender, EventArgs e) { // 验证 if (!check()) { DialogResult = DialogResult.None; return; } DialogResult = DialogResult.OK; // 创建一个瓦斯浓度探头数据实体 var gasConcentrationProbeDataEntity = new GasConcentrationProbeData(); // 探头编号 gasConcentrationProbeDataEntity.Probe.ProbeId = Convert.ToString(_lstProbeName.SelectedValue); // 探头数值 double dProbeValue = 0; if (double.TryParse(txtProbeValue.Text.Trim(), out dProbeValue)) { gasConcentrationProbeDataEntity.ProbeValue = dProbeValue; } // 记录时间 gasConcentrationProbeDataEntity.RecordTime = dtpRecordTime.Value; // 记录类型 gasConcentrationProbeDataEntity.RecordType = Const_GE.RECORDTYPE_PEOPLE; OPERATION_TYPE opType; var bResult = false; if (_bllType == "add") { // 瓦斯浓度探头数据登录 gasConcentrationProbeDataEntity.CreateAndFlush(); bResult = true; opType = OPERATION_TYPE.ADD; if (bResult) { #region 通知服务器预警数据已更新 var workingfaceEnt = selectTunnelUserControl1.SelectedTunnel.WorkingFace; var msg = new UpdateWarningDataMsg(workingfaceEnt.WorkingFaceId, selectTunnelUserControl1.SelectedTunnel.TunnelId, DayReportHc.TableName, opType, gasConcentrationProbeDataEntity.RecordTime); SocketUtil.SendMsg2Server(msg); #endregion } } else { // 主键 gasConcentrationProbeDataEntity.ProbeDataId = Convert.ToInt32(_iPK); // 探头管理信息修改 gasConcentrationProbeDataEntity.SaveAndFlush(); opType = OPERATION_TYPE.UPDATE; #region 通知服务器预警数据已更新 var workingfaceEnt = selectTunnelUserControl1.SelectedTunnel.WorkingFace; var msg = new UpdateWarningDataMsg(workingfaceEnt.WorkingFaceId, selectTunnelUserControl1.SelectedTunnel.TunnelId, DayReportHc.TableName, opType, gasConcentrationProbeDataEntity.RecordTime); SocketUtil.SendMsg2Server(msg); #endregion } // 添加\修改成功的场合 if (bResult) { // 如何探头编号发生改变则不更新管理画面的farpoint if (GasConcentrationProbeDataManamement._probeId != Convert.ToString(_lstProbeName.SelectedValue)) { GasConcentrationProbeDataManamement._iDisposeFlag = Const.DISPOSE_FLAG_ZERO; } } }
static ConfigurationSettings() { HandleRetrytimes = ConfigurationManager.AppSettings["umizoo.retry_count"].ChangeIfError(5); HandleRetryInterval = ConfigurationManager.AppSettings["umizoo.retry_interval"].ChangeIfError(1000); MaxRequests = ConfigurationManager.AppSettings["umizoo.request_limit"].ChangeIfError(2000); OperationTimeout = ConfigurationManager.AppSettings["umizoo.request_timeout"].ChangeIfError(120); CommandFilterEnabled = ConfigurationManager.AppSettings["umizoo.filter_command"].ChangeIfError(false); QueryFilterEnabled = ConfigurationManager.AppSettings["umizoo.filter_query"].ChangeIfError(false); ParallelQueryThead = ConfigurationManager.AppSettings["umizoo.thread_query"].ChangeIfError(1); OuterAddress = ConfigurationManager.AppSettings["umizoo.service_outeraddress"].IfEmpty(() => string.Format("{0}:9999", SocketUtil.GetLocalIPV4())); InnerAddress = ConfigurationManager.AppSettings["umizoo.service_inneraddress"].IfEmpty(() => string.Format("{0}:9999", SocketUtil.GetLocalIPV4("192.", "10.", "127."))); ServiceName = ConfigurationManager.AppSettings["umizoo.service_name"].IfEmpty("Umizoo"); ContextType = ConfigurationManager.AppSettings["umizoo.service_name"].IfEmpty("web"); }
/// <summary> /// 添加回采日报 /// </summary> private void insertDayReportHCInfo() { var workingFace = selectWorkingfaceSimple1.SelectedWorkingFace; var dayReportHCEntityList = new List <DayReportHc>(); for (var i = 0; i < dgrdvDayReportHC.RowCount; i++) { var dayReportHCEntity = new DayReportHc(); // 最后一行为空行时,跳出循环 if (i == dgrdvDayReportHC.RowCount - 1) { break; } /**回采日报实体赋值**/ //队别名称 dayReportHCEntity.Team = (Team)cboTeamName.SelectedItem; //绑定回采面编号 dayReportHCEntity.WorkingFace = selectWorkingfaceSimple1.SelectedWorkingFace; var cells = dgrdvDayReportHC.Rows[i].Cells; //日期 if (cells[C_DATE].Value != null) { dayReportHCEntity.DateTime = Convert.ToDateTime(cells[C_DATE].Value.ToString()); } else { Alert.alert("请录入进尺时间"); DialogResult = DialogResult.None; return; } //填报人 dayReportHCEntity.Submitter = cboSubmitter.Text; //工作制式 if (rbtn38.Checked) { dayReportHCEntity.WorkTimeStyle = rbtn38.Text; } if (rbtn46.Checked) { dayReportHCEntity.WorkTimeStyle = rbtn46.Text; } //班次 if (cells[C_WORK_TIME].Value != null) { dayReportHCEntity.WorkTime = cells[C_WORK_TIME].Value.ToString(); } //工作内容 if (cells[C_WORK_CONTENT].Value != null) { dayReportHCEntity.WorkInfo = cells[C_WORK_CONTENT].Value.ToString(); } //回采进尺 if (cells[C_WORK_PROGRESS].Value != null) { dayReportHCEntity.JinChi = Convert.ToDouble(cells[C_WORK_PROGRESS].Value); } //备注 if (cells[C_COMMENTS].Value != null) { dayReportHCEntity.Remarks = cells[C_COMMENTS].Value.ToString(); } //BID dayReportHCEntity.BindingId = IDGenerator.NewBindingID(); //添加到dayReportHCEntityList中 dayReportHCEntityList.Add(dayReportHCEntity); } var bResult = false; //循环添加 foreach (var dayReportHcEntity in dayReportHCEntityList) { // 在图中绘制回采进尺 if (workingFace != null) { var hcjc = dayReportHcEntity.JinChi; var bid = dayReportHcEntity.BindingId; var workingFaceHc = WorkingFaceHc.FindByWorkingFace(workingFace); AddHcjc(workingFaceHc.TunnelZy.TunnelId, workingFaceHc.TunnelFy.TunnelId, workingFaceHc.TunnelQy.TunnelId, workingFaceHc.TunnelZy.TunnelWid, workingFaceHc.TunnelFy.TunnelWid, workingFaceHc.TunnelQy.TunnelWid, hcjc, bid); dayReportHcEntity.SaveAndFlush(); bResult = true; } else { Log.Fatal("[添加回采日报]:工作面实体为空值。"); } } //添加失败 if (!bResult) { Alert.alert(Const_MS.MSG_UPDATE_FAILURE); } else { // 工作面坐标已经改变,需要更新工作面信息 Log.Debug("发送地址构造消息------开始"); // 通知服务端回采进尺已经添加 var msg = new UpdateWarningDataMsg(selectWorkingfaceSimple1.SelectedWorkingFace.WorkingFaceId, Const.INVALID_ID, DayReportHc.TableName, OPERATION_TYPE.ADD, DateTime.Now); SocketUtil.SendMsg2Server(msg); Log.Debug("发送地址构造消息------完成" + msg); } }
/// <summary> /// 修改回采日报信息 /// </summary> private void UpdateDayReportHcInfo() { _dayReportHc.WorkingFace.WorkingFaceId = selectWorkingfaceSimple1.SelectedWorkingFace.WorkingFaceId; //队别名称 _dayReportHc.Team.TeamId = Convert.ToInt32(cboTeamName.SelectedValue); //日期 //_dayReportHCEntity.DateTime = dtpDate.Value; //填报人 _dayReportHc.Submitter = cboSubmitter.Text; //工作制式 if (rbtn38.Checked) { _dayReportHc.WorkTimeStyle = rbtn38.Text; } if (rbtn46.Checked) { _dayReportHc.WorkTimeStyle = rbtn46.Text; } var cells = dgrdvDayReportHC.Rows[0].Cells; //创建日期 if (cells[C_DATE].Value != null) { _dayReportHc.DateTime = Convert.ToDateTime(cells[C_DATE].Value.ToString()); } //班次 if (cells[C_WORK_TIME].Value != null) { _dayReportHc.WorkTime = cells[C_WORK_TIME].Value.ToString(); } //工作内容 if (cells[C_WORK_CONTENT].Value != null) { _dayReportHc.WorkInfo = cells[C_WORK_CONTENT].Value.ToString(); } //回采进尺 if (cells[C_WORK_PROGRESS].Value != null) { _dayReportHc.JinChi = Convert.ToDouble(cells[C_WORK_PROGRESS].Value); } //备注 if (cells[C_COMMENTS].Value != null) { _dayReportHc.Remarks = cells[C_COMMENTS].Value.ToString(); } //提交修改 _dayReportHc.SaveAndFlush(); var bResult = true; //绘制回采进尺图形 var hcjc = _dayReportHc.JinChi; var bid = _dayReportHc.BindingId; var workingFace = selectWorkingfaceSimple1.SelectedWorkingFace; var workingFaceHc = WorkingFaceHc.FindByWorkingFace(workingFace); UpdateHcjc(workingFaceHc.TunnelZy.TunnelId, workingFaceHc.TunnelFy.TunnelId, workingFaceHc.TunnelQy.TunnelId, hcjc, bid, workingFaceHc.TunnelZy.TunnelWid, workingFaceHc.TunnelFy.TunnelWid, workingFaceHc.TunnelQy.TunnelWid); // 通知服务器数据已经修改 var msg = new UpdateWarningDataMsg(workingFace.WorkingFaceId, workingFaceHc.TunnelQy.TunnelId, DayReportHc.TableName, OPERATION_TYPE.UPDATE, DateTime.Now); SocketUtil.SendMsg2Server(msg); }
private void btn_savePath_Click(object sender, EventArgs e) { try { ///Ask user for a directory to save the file in using (SaveFileDialog saveFileDlg = new SaveFileDialog()) { saveFileDlg.AutoUpgradeEnabled = true; saveFileDlg.Title = "Save file"; saveFileDlg.DefaultExt = ""; saveFileDlg.Filter = "All files (*.*)|*.*"; ///Set the file name, so the file is saved with same name ///as the sender is sending saveFileDlg.FileName = this._data.FileName; if (saveFileDlg.ShowDialog() == DialogResult.OK) { using (Stream saveStream = saveFileDlg.OpenFile()) { ///Setup the progress bar this.progress.Maximum = this._data.FileLen; this.progress.Value = 0; int received = 0; ///While there is still some data to receive while (received < this._data.FileLen) { ///We receive file in size of 1024 bytes chunks int bufferSize = 1024; ///If there is less then 1024 bytes to receive if (this._data.FileLen - received < 1024) { bufferSize = this._data.FileLen - received; } byte[] buffer = new byte[bufferSize]; ///function is used to receive the buffer from the server, look that it is used both in server and client. ///Receive data from client SocketUtil.Receive(this._client, buffer); received += bufferSize; ///Write that data to file saveStream.Write(buffer, 0, buffer.Length); ///Update the progress bar this.progress.Increment(bufferSize); } saveStream.Close(); } UIMessage.Info("File receive successful", "File receive"); } else { ///Disconnect the client this._receiver.DiconnectClient(this._client); } } } catch (Exception exc) { UIMessage.Error(exc.Message, "Receive file"); } this.Close(); }
private void OnAddressFullyRead(IAsyncResult ar) { if (_closed) { return; } try { int bytesRead = _connection.EndReceive(ar); var states = (object[])ar.AsyncState; int bytesRemain = (int)states[0]; var onSuccess = (Action)states[1]; if (bytesRead >= bytesRemain) { _firstPacketLength = bytesRead + 2; int atyp = _connetionRecvBuffer[0]; string dstAddr = "Unknown"; int dstPort = -1; switch (atyp) { case ATYP_IPv4: // IPv4 address, 4 bytes dstAddr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString(); dstPort = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6]; _addrBufLength = ADDR_ATYP_LEN + 4 + ADDR_PORT_LEN; if (!P2pLib.GetInstance().global_mode_) { try { string ip_country = P2pLib.GetInstance().GetIpCountry(dstAddr.ToString()); if (ip_country == P2pLib.GetInstance().local_country_) { P2pLib.GetInstance().AddLocalSites(dstAddr); } } catch { } } break; case ATYP_DOMAIN: // domain name, length + str int len = _connetionRecvBuffer[1]; dstAddr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len); dstPort = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3]; if (!P2pLib.GetInstance().global_mode_) { try { IPHostEntry IPinfo = Dns.GetHostEntry(dstAddr); //显示IP地址 int valid_count = 0; foreach (IPAddress IP in IPinfo.AddressList) { string country = P2pLib.GetInstance().GetIpCountry(IP.ToString()); if (country == P2pLib.GetInstance().local_country_) { valid_count++; } } if (valid_count > (IPinfo.AddressList.Length / 2)) { P2pLib.GetInstance().AddLocalSites(dstAddr); } } catch (Exception e) { } } _addrBufLength = ADDR_ATYP_LEN + 1 + len + ADDR_PORT_LEN; break; case ATYP_IPv6: // IPv6 address, 16 bytes dstAddr = $"[{new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray())}]"; dstPort = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18]; _addrBufLength = ADDR_ATYP_LEN + 16 + ADDR_PORT_LEN; break; } if (_config.isVerboseLogging) { Logging.Info($"connect to {dstAddr}:{dstPort}"); } _destEndPoint = SocketUtil.GetEndPoint(dstAddr, dstPort); onSuccess.Invoke(); /* StartConnect() */ } else { Logging.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()"); Close(); } } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
public void SetIPEndPoint(string address, int port) { Address = address; Port = port; ip = SocketUtil.ParseIP(Address); }
private async Task StartConnect() { SaeaAwaitable serverSaea = null; try { CreateRemote(); _serverSocket = new Socket(SocketType.Stream, ProtocolType.Tcp); _serverSocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true); _serverSocket.SetTFO(); // encrypt and attach encrypted buffer to ConnectAsync serverSaea = _argsPool.Rent(); var realSaea = serverSaea.Saea; var encryptedbufLen = -1; Logging.Dump("StartConnect(): enc addrBuf", _addrBuf, _addrBufLength); lock (_encryptionLock) { _encryptor.Encrypt(_addrBuf, _addrBufLength, realSaea.Buffer, out encryptedbufLen); } Logging.Debug("StartConnect(): addrBuf enc len " + encryptedbufLen); if (_remainingBytesLen > 0) { Logging.Debug($"StartConnect(): remainingBytesLen: {_remainingBytesLen}"); var encRemainingBufLen = -1; byte[] tmp = new byte[4096]; Logging.Dump("StartConnect(): enc remaining", _remainingBytes, _remainingBytesLen); lock (_encryptionLock) { _encryptor.Encrypt(_remainingBytes, _remainingBytesLen, tmp, out encRemainingBufLen); } Logging.Debug("StartConnect(): remaining enc len " + encRemainingBufLen); Buffer.BlockCopy(tmp, 0, realSaea.Buffer, encryptedbufLen, encRemainingBufLen); encryptedbufLen += encRemainingBufLen; } Logging.Debug("actual enc buf len " + encryptedbufLen); realSaea.RemoteEndPoint = SocketUtil.GetEndPoint(_server.server, _server.server_port); realSaea.SetBuffer(0, encryptedbufLen); var err = await _serverSocket.ConnectAsync(serverSaea); if (err != SocketError.Success) { Logging.Error($"StartConnect: {err}"); Close(); return; } Logging.Debug("remote connected"); if (serverSaea.Saea.BytesTransferred != encryptedbufLen) { // not sent all data, it may caused by TFO, disable it Logging.Info("Disable TCP Fast Open due to initial send failure"); Program.DisableTFO(); Close(); return; } _argsPool.Return(serverSaea); serverSaea = null; if (_config.isVerboseLogging) { Logging.Info($"Socket connected to ss server: {_server.FriendlyName()}"); } Task.Factory.StartNew(StartPipe, TaskCreationOptions.PreferFairness).Forget(); } catch (AggregateException agex) { foreach (var ex in agex.InnerExceptions) { Logging.LogUsefulException(ex); } Close(); } catch (Exception e) { Logging.LogUsefulException(e); Close(); } finally { _argsPool.Return(serverSaea); serverSaea = null; } }
private void OnAddressFullyRead(IAsyncResult ar) { if (_closed) { return; } try { int bytesRead = _connection.EndReceive(ar); int bytesRemain = (int)ar.AsyncState; if (bytesRead >= bytesRemain) { _firstPacketLength = bytesRead + 2; int atyp = _connetionRecvBuffer[0]; string dst_addr = "Unknown"; int dst_port = -1; switch (atyp) { case 1: // IPv4 address, 4 bytes dst_addr = new IPAddress(_connetionRecvBuffer.Skip(1).Take(4).ToArray()).ToString(); dst_port = (_connetionRecvBuffer[5] << 8) + _connetionRecvBuffer[6]; break; case 3: // domain name, length + str int len = _connetionRecvBuffer[1]; dst_addr = System.Text.Encoding.UTF8.GetString(_connetionRecvBuffer, 2, len); dst_port = (_connetionRecvBuffer[len + 2] << 8) + _connetionRecvBuffer[len + 3]; break; case 4: // IPv6 address, 16 bytes dst_addr = $"[{new IPAddress(_connetionRecvBuffer.Skip(1).Take(16).ToArray())}]"; dst_port = (_connetionRecvBuffer[17] << 8) + _connetionRecvBuffer[18]; break; } if (_config.isVerboseLogging) { Logging.Info($"connect to {dst_addr}:{dst_port}"); } _destEndPoint = SocketUtil.GetEndPoint(dst_addr, dst_port); if (_command == 1) { byte[] response = { 5, 0, 0, 1, 0, 0, 0, 0, 0, 0 }; _connection.BeginSend(response, 0, response.Length, SocketFlags.None, new AsyncCallback(ResponseCallback), null); } else if (_command == 3) { HandleUDPAssociate(); } } else { Logging.Debug("failed to recv data in Shadowsocks.Controller.TCPHandler.OnAddressFullyRead()"); Close(); } } catch (Exception e) { Logging.LogUsefulException(e); Close(); } }
private void MainForm_WM_Load(object sender, EventArgs e) { SocketUtil.DoInitilization(); ////////////////////////////////////////////////////// ///文件菜单 mapControl_WM.LoadMxFile(Application.StartupPath + "\\" + ConfigManager.Instance.getValueByKey(ConfigConst.CONFIG_MXD_FILE)); //this.mapControl_WM.LoadMxFile(Application.StartupPath + "\\local.mxd"); toolStrip1.AxMap = mapControl_WM; m_FileMenu.AxMapControl = mapControl_WM; //传入MapControl控件 ////////////////////////////////////////////////////// //绘制基本图元工具条 //加载测试数 var mapControl = (IMapControl3)mapControl_WM.Object; var toolbarControl = (IToolbarControl)toolBar_WM.Object; //绑定控件 toolBar_WM.SetBuddyControl(mapControl); tocControl_WM.SetBuddyControl(mapControl); //获得工作空间 //string strProvide = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="; //string strDataSource = Application.StartupPath + @"\GasWarning-ChengZhuang.mdb"; //MDBOperation.GetODbConnection(strProvide + strDataSource); //IWorkspaceFactory workspaceFactory = new AccessWorkspaceFactory(); //IWorkspace workspace = workspaceFactory.OpenFromFile(strDataSource, 0); //this.toolBar_WM.AddItem("esriControls.ControlsMapNavigationToolbar"); //this.toolBar_WM.AddItem("esriControls.ControlsMapRefreshViewCommand", 0, -1, false, 0, esriCommandStyles.esriCommandStyleIconOnly); //给全局变量赋值 DataEditCommon.g_tbCtlEdit = toolbarControl; DataEditCommon.g_pAxMapControl = mapControl_WM; DataEditCommon.g_axTocControl = tocControl_WM; DataEditCommon.load(); //添加Toolbar //toolBar_WM.AddToolbarDef(new GIS_ToolbarView()); //toolBar_WM.AddToolbarDef(new GIS_ToolbarEdit(mapControl_WM, mapControl, toolbarControl, // DataEditCommon.g_pCurrentWorkSpace)); ////this.toolBar_WM.AddToolbarDef(new GIS_ToolbarSpecial()); //toolBar_WM.AddToolbarDef(new GIS_ToolbarModify()); //toolBar_WM.AddToolbarDef(new GIS_ToolbarBasic()); AddToolBar.Addtool(mapControl_WM, mapControl, toolbarControl, DataEditCommon.g_pCurrentWorkSpace); Global.SetInitialParams(mapControl_WM.ActiveView); AutoUpdater.Start("http://bltmld.vicp.cc:8090/sys5/update.xml"); //注册更新预警结果事件 SocketUtil.GetClientSocketInstance().OnMsgUpdateWarningResult += UpdateWarningResultUi; var msg = new SocketMessage(COMMAND_ID.REGISTER_WARNING_RESULT_NOTIFICATION_ALL, DateTime.Now); SocketUtil.SendMsg2Server(msg); //浮动工具条中文设置 DXSeting.floatToolsLoadSet(); ShowLatestWarningResult(); }
/// <summary> /// Send data to destination computer /// </summary> /// <param name="buffer"></param> public void Send(byte[] buffer) { SocketUtil.Send(this._socket, buffer); }