C# Task<bool>这句是啥意思

各位大神,下面代码中的Task autoRec = Task.Factory.StartNew(() =>这句是什么意思啊,查了半天、还是不理解!
Task autoRec = Task.Factory.StartNew(() =>
{
string newPdtDir = _curPdtDir.Substring(0, _curPdtDir.LastIndexOf("\")) + "\" + copyNewPdtName;
FileModule.CopyDirectory(_curPdtDir, newPdtDir);

            productList_UpdateLst();

            return autoChangeProduct(copyNewPdtName, ref strMsg);
        });
c#

1个回答

Task.Factory.StartNew 启动一个新的线程? 哪里不理解 是不理解写法吗?TaskFactory.StartNew Method (Action) 这个是原函数

https://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx 这里面有介绍 action的写法 可以理解为 action就是 这个线程的执行调用方法,

你开启了一个线程,线程是为了做事情,做事情就需要实现怎么做,所以c#里面就是开启一个线程并且指定在这个线程里面执行一个action的意思

ycigwy
雍王爷 是不是可以这样理解:Task.Factory.StartNew(() =>是启动一个新的线程, =>{就是这个线程执行的方法?
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
c#有关异步的问题: async await Task

比方说我现在有个api:a页面中有个 a1方法, a1异步调用a2方法, a2异步调用a3方法, a3中是执行数据库查询操作的,那么我的a3中数据库查询也必须要用异步数据库查询方法吗?如果是同步查询数据库,那么前面的异步起作用了吗?

初次使用Task<TResult>关于阻塞主线程求指教

做了一个winform程序,点击一个按钮需要调用一个复杂耗时的方法,总是造成主界面卡死,据说Task可以解决此类情况,就上网查资料模仿,后来发现还是卡死,代码段如下: City ct = (City)cbxCity.SelectedItem; bool checkCom = cBoxDisCom.Checked; Task<DataSet> t = null; t = new Task<DataSet>(() => ImportService.FilterForRaw2(dt, ct, checkCom)); t.Start(); t.Wait(); dgvExportData.DataSource = t.Result.Tables[1]; dgv1.DataSource = t.Result.Tables[0]; 请问有没有办法可以既获取Task产生的结果t.Result,又不会造成主线程阻塞

C#同/异步委托使用和调用,请指教

public delegate void GetResultEventHandler(object sender, bool IsSucceed, string DataResults); public event GetResultEventHandler OnGetInfoCompleted; public void GetPostHtmlResults(string GetURL, int GetTimeOut) { HttpWebRequest request = HttpWebRequest.CreateHttp(GetURL); request.Method = "GET"; request.ContinueTimeout = GetTimeOut; request.BeginGetResponse(GetInfoCompleted, request); } private void GetInfoCompleted(IAsyncResult asyncResult) { try { HttpWebRequest webRequest = asyncResult.AsyncState as HttpWebRequest; HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult); Stream streamResult = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(streamResult, Encoding.UTF8); if (OnGetInfoCompleted != null) OnGetInfoCompleted(this, true, reader.ReadToEnd()); } catch (WebException ex) { OnGetInfoCompleted(this, false, ex.Message.ToString()); } } 请问这个同/异步委托对不对,还有怎样调用它,谢谢!

以下C++代码如何翻译成C#代码?

``` typedef int s32,BOOL32; #if defined(_WIN64) || defined(WIN64) ||defined (__LP64__) || defined (__64BIT__) || defined (_LP64) || (__WORDSIZE == 64) typedef unsigned int u32; #define KD_PTR void* #else typedef unsigned long u32; #define KD_PTR u32 #endif typedef unsigned char u8; typedef unsigned short u16; typedef short s16; typedef char s8; ``` ``` typedef enum eTransType { emTransChnCOMPort = 0, // 设备COM口透明数据 emTransChnCameraTaskConfig = 1, // 摄像机任务配置数据 emTransChnExtData = 2, // 透明数据,支持请求应答通知三态模型 }TransChnType; typedef struct tagTransData { tagTransData() { memset(m_byTransBuffer,0,sizeof(m_byTransBuffer)); m_wTransBufferLen = 0; m_byAppType = 0; } u8 m_byTransBuffer[MAX_TRANSCHAN_DATA_LEN+1]; u16 m_wTransBufferLen; s8 m_byAppType; } TTransChnData; typedef struct tagTransData_V2 { tagTransData_V2() { memset(m_byTransBuffer,0,sizeof(m_byTransBuffer)); m_wTransBufferLen = 0; m_byAppType = 0; m_TransChnType = emTransChnCOMPort; } u8 m_byTransBuffer[MAX_TRANSCHAN_DATA_LEN+1]; u16 m_wTransBufferLen; u16 m_byAppType; // 透明通道消息类型 TransChnType m_TransChnType; // 透明通道类型 } TTransChnData_V2; typedef struct tagTransData_V3 { tagTransData_V3() { m_pTransBuffer = NULL; m_wTransBufferLen = 0; m_byAppType = 0; m_TransChnType = emTransChnCOMPort; } u8 *m_pTransBuffer; u16 m_wTransBufferLen; // 透明串口数据大小最大值是8KB u16 m_byAppType; // 透明通道消息类型 TransChnType m_TransChnType; // 透明通道类型 } TTransChnData_V3; typedef struct tagTransDataRsp { tagTransDataRsp() { m_pTransBuffer = NULL; m_wTransBufferLen = 0; m_byAppType = 0; memset(m_szUserName, 0, sizeof(m_szUserName)); m_nPtzLevel = 0; m_dwBeginTime = 0; m_dwEndTime = 0; m_bHasNotify = FALSE; m_nErrorCode = 0; memset(m_szErrorDesc, 0, sizeof(m_szErrorDesc)); } u8 *m_pTransBuffer; // 透明通道应答数据,大小至少为8KB。内存由上层应用维护。 u16 m_wTransBufferLen; // 透明通道应答数据大小 u16 m_byAppType; // 透明通道消息类型 char m_szUserName[MAX_NAME_LEN + 1]; int m_nPtzLevel; u32 m_dwBeginTime; u32 m_dwEndTime; BOOL32 m_bHasNotify; int m_nErrorCode; char m_szErrorDesc[MAX_DESC_LEN + 1]; } TTransChnDataRsp; ``` ``` KDM_MCUSDK_API BOOL32 STDCALL Kdm_SendTransData(IN void *pMcuHandle, IN DEVCHN tDevChn, IN TTransChnData *pTransData, OUT u32 *pErrorCode); KDM_MCUSDK_API BOOL32 STDCALL Kdm_SendTransData_V2(IN void *pMcuHandle, IN DEVCHN tDevChn, IN TTransChnData_V2 *pTransData, OUT u32 *pErrorCode); KDM_MCUSDK_API BOOL32 STDCALL Kdm_SendTransData_V3(IN void *pMcuHandle, IN DEVCHN tDevChn, IN TTransChnData_V3 *pTransData, OUT TTransChnDataRsp *pTransDataRsp, OUT u32 *pErrorCode); ``` ``` void CMainFrame::SaveSensorConfigInfo() { u32 dwErrorCode = 0; TCHAR szContent[MAX_PATH] = {0}; CStdString strTemp; strTemp = m_pConfigNvrIDEdit->GetText(); strcpy(m_tSensorCfgParam.achTemID, strTemp.GetData()); strTemp = m_pConfigWidthEdit->GetText(); strcpy(m_tSensorCfgParam.achJieMianKuanDu, strTemp.GetData()); for (int nIndex = 0; nIndex < NVR_MAX_SENSOR_OSD_LINE_NUM; ++nIndex) { strTemp = m_pArrayConfigLineEdit[nIndex]->GetText(); strcpy(m_tSensorCfgParam.achOsdLine[nIndex], strTemp.GetData()); } strTemp = m_pConfigOSDXEdit->GetText(); m_tSensorCfgParam.nOsdX = atoi(strTemp.GetData()); strTemp = m_pConfigOSDYEdit->GetText(); m_tSensorCfgParam.nOsdY = atoi(strTemp.GetData()); strTemp = m_pConfigFtpAddressEdit->GetText(); strcpy(m_tSensorCfgParam.achFtpServerIp, strTemp.GetData()); strTemp = m_pConfigFtpPortEdit->GetText(); m_tSensorCfgParam.wFtpServerPort = atoi(strTemp.GetData()); strTemp = m_pConfigFtpUsrnameEdit->GetText(); strcpy(m_tSensorCfgParam.achFtpServerUsr, strTemp.GetData()); strTemp = m_pConfigFtpPasswordEdit->GetText(); strcpy(m_tSensorCfgParam.achFtpServerPwd, strTemp.GetData()); strTemp = m_pConfigHttpAddressEdit->GetText(); strcpy(m_tSensorCfgParam.achHttpServerIp, strTemp.GetData()); strTemp = m_pConfigHttpPortEdit->GetText(); m_tSensorCfgParam.wHttpServerPort = atoi(strTemp.GetData()); strTemp = m_pConfigHttpUploadURLEdit->GetText(); strcpy(m_tSensorCfgParam.achHttpUpLoadUrl, strTemp.GetData()); strTemp = m_pConfigHttpKeepURLEdit->GetText(); strcpy(m_tSensorCfgParam.achHttpKeepAliveUrl, strTemp.GetData()); int nSel = m_pPlatformNvrCombo->GetCurSel(); if (nSel != -1) { int nTag = m_pPlatformNvrCombo->GetItemAt(nSel)->GetTag(); // 透明传输 DEVCHN devChn; memset(&devChn, 0, sizeof(devChn)); devChn.deviceID = m_vcDevInfo[nTag].deviceID; devChn.domainID = m_vcDevInfo[nTag].domainID; TNvrTransData tNvrTransData; memset(&tNvrTransData, 0, sizeof(tNvrTransData)); tNvrTransData.wNvrMsgType = PLAT_NVR_CONFIG_SENSOR_REQ; tNvrTransData.wNvrBuffLen = sizeof(m_tSensorCfgParam); memcpy(tNvrTransData.m_abyNvrBuff, &m_tSensorCfgParam, sizeof(m_tSensorCfgParam)); TTransChnData_V3 tTransChnData_V3; memset(&tTransChnData_V3, 0, sizeof(tTransChnData_V3)); tTransChnData_V3.m_pTransBuffer = (u8*)&tNvrTransData; tTransChnData_V3.m_wTransBufferLen = sizeof(tNvrTransData); tTransChnData_V3.m_TransChnType = emTransChnExtData; TTransChnDataRsp tTransChnDataRsp; memset(&tTransChnDataRsp, 0, sizeof(tTransChnDataRsp)); tTransChnDataRsp.m_pTransBuffer = m_byteTransChnDataBuffer; tTransChnDataRsp.m_wTransBufferLen = sizeof(m_byteTransChnDataBuffer); BOOL32 bRet = Kdm_SendTransData_V3(m_pMcuSdkHandle, devChn, &tTransChnData_V3, &tTransChnDataRsp, &dwErrorCode); if (!bRet) { sprintf(szContent, "保存设备配置数据失败,errcode:%u", dwErrorCode); GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } else { memset(&tNvrTransData, 0, sizeof(tNvrTransData)); memcpy(&tNvrTransData, m_byteTransChnDataBuffer, sizeof(tNvrTransData)); if (tNvrTransData.wErrorCode != 0) { sprintf(szContent, "保存设备配置数据失败,errcode:%u", tNvrTransData.wErrorCode); GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } } } } ``` 尝试修改为以下C#代码,运行成功,但是执行时候报错: ``` [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct tagTransData { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 513)] public byte[] m_byTransBuffer; public ushort m_wTransBufferLen; public char m_byAppType; } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public struct tagTransData_V2 { [MarshalAs(UnmanagedType.ByValArray, SizeConst = 513)] public byte[] m_byTransBuffer; public ushort m_wTransBufferLen; public ushort m_byAppType; // 透明通道消息类型 public eTransType m_TransChnType; // 透明通道类型 } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public unsafe struct tagTransData_V3 { public byte* m_pTransBuffer; public ushort m_wTransBufferLen; // 透明串口数据大小最大值是8KB public ushort m_byAppType; // 透明通道消息类型 public eTransType m_TransChnType; // 透明通道类型 } [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Unicode)] public unsafe struct tagTransDataRsp { public byte* m_pTransBuffer; // 透明通道应答数据,大小至少为8KB。内存由上层应用维护。 public ushort m_wTransBufferLen; // 透明通道应答数据大小 public ushort m_byAppType; // 透明通道消息类型 public char* m_szUserName; public int m_nPtzLevel; public uint m_dwBeginTime; public uint m_dwEndTime; public uint m_bHasNotify; public int m_nErrorCode; public char* m_szErrorDesc; } ``` ``` [DllImport(@"mcusdk.dll")] public extern static uint Kdm_SendTransData(IntPtr pMcuHandle, DEVCHN tDevChn, tagTransData pTransData, ref uint pErrorCode); [DllImport(@"mcusdk.dll")] public extern static uint Kdm_SendTransData_V2(IntPtr pMcuHandle, DEVCHN tDevChn, tagTransData_V2 TransData, ref uint pErrorCode); [DllImport(@"mcusdk.dll")] public extern static uint Kdm_SendTransData_V3(IntPtr pMcuHandle, DEVCHN tDevChn, tagTransData_V3 pTransData, ref tagTransDataRsp pTransDataRsp, ref uint pErrorCode); ``` ``` private unsafe void btnSave_Click(object sender, EventArgs e) { uint dwErrorCode = 0; TSensorCfgParam m_tSensorCfgParam=new TSensorCfgParam(); sbyte[] szContent = new sbyte[DefineConstants.MAX_PATH]; m_tSensorCfgParam.achTemID = txtNVRID.Text; m_tSensorCfgParam.achJieMianKuanDu = txtWidth.Text; //for (int nIndex = 0; nIndex < NVR_MAX_SENSOR_OSD_LINE_NUM; ++nIndex) //{ // strTemp = m_pArrayConfigLineEdit[nIndex].GetText(); // m_tSensorCfgParam.achOsdLine[nIndex] = strTemp.GetData(); //} //strTemp = m_pConfigOSDXEdit.GetText(); //m_tSensorCfgParam.nOsdX = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigOSDYEdit.GetText(); //m_tSensorCfgParam.nOsdY = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigFtpAddressEdit.GetText(); //m_tSensorCfgParam.achFtpServerIp = strTemp.GetData(); //strTemp = m_pConfigFtpPortEdit.GetText(); //m_tSensorCfgParam.wFtpServerPort = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigFtpUsrnameEdit.GetText(); //m_tSensorCfgParam.achFtpServerUsr = strTemp.GetData(); //strTemp = m_pConfigFtpPasswordEdit.GetText(); //m_tSensorCfgParam.achFtpServerPwd = strTemp.GetData(); //strTemp = m_pConfigHttpAddressEdit.GetText(); //m_tSensorCfgParam.achHttpServerIp = strTemp.GetData(); //strTemp = m_pConfigHttpPortEdit.GetText(); //m_tSensorCfgParam.wHttpServerPort = Convert.ToInt32(strTemp.GetData()); //strTemp = m_pConfigHttpUploadURLEdit.GetText(); //m_tSensorCfgParam.achHttpUpLoadUrl = strTemp.GetData(); //strTemp = m_pConfigHttpKeepURLEdit.GetText(); //m_tSensorCfgParam.achHttpKeepAliveUrl = strTemp.GetData(); int nSel = lbDevice.SelectedIndex; if (nSel != -1) { //int nTag = m_pPlatformNvrCombo.GetItemAt(nSel).GetTag(); // 透明传输 DEVCHN devChn = new DEVCHN(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(devChn, 0, sizeof(DEVCHN)); devChn.deviceID = deviceList[nSel].deviceID; devChn.domainID = deviceList[nSel].domainID; TNvrTransData tNvrTransData = new TNvrTransData(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(tNvrTransData, 0, sizeof(TNvrTransData)); tNvrTransData.wNvrMsgType = DefineConstants.PLAT_NVR_CONFIG_SENSOR_REQ; //tNvrTransData.wNvrBuffLen = sizeof(m_tSensorCfgParam); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //Comm.memcpy(tNvrTransData.m_abyNvrBuff, m_tSensorCfgParam, sizeof(m_tSensorCfgParam)); tagTransData_V3 tTransChnData_V3 = new tagTransData_V3(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(tTransChnData_V3, 0, sizeof(TTransChnData_V3)); tTransChnData_V3.m_pTransBuffer = (byte)&tNvrTransData; //tTransChnData_V3.m_pTransBuffer = (byte*) ref (tNvrTransData)[0]; //tTransChnData_V3.m_wTransBufferLen = sizeof(TNvrTransData); tTransChnData_V3.m_TransChnType = eTransType.emTransChnExtData; tagTransDataRsp tTransChnDataRsp = new tagTransDataRsp(); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //Comm.memset(tTransChnDataRsp, 0, sizeof(tagTransDataRsp)); m_byteTransChnDataBuffer = new byte[8 * 1024]; tTransChnDataRsp.m_pTransBuffer = (byte*)m_byteTransChnDataBuffer[0]; //tTransChnDataRsp.m_wTransBufferLen = sizeof(m_byteTransChnDataBuffer); uint bRet = myAPI.Kdm_SendTransData_V3(mcuHandle, devChn, tTransChnData_V3, ref tTransChnDataRsp, ref dwErrorCode); if (bRet == 0) { //szContent = string.Format("保存设备配置数据失败,errcode:{0:D}", dwErrorCode); //GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } else { //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memset' has no equivalent in C#: //memset(tNvrTransData, 0, sizeof(TNvrTransData)); //C++ TO C# CONVERTER CRACKED BY X-CRACKER 2017 TODO TASK: The memory management function 'memcpy' has no equivalent in C#: //memcpy(tNvrTransData, m_byteTransChnDataBuffer, sizeof(TNvrTransData)); if (tNvrTransData.wErrorCode != 0) { //szContent = string.Format("保存设备配置数据失败,errcode:{0:D}", tNvrTransData.wErrorCode); //GM.DuiMessageBox(m_hWnd, szContent, "kedacom", MB_OK); } } } } ``` 求大神翻译

C# Linq 对long进行比较时出现异常

我在Core 3.1中使用MySql.Data.EntityFramework遇到了一个问题。 mysql中id的数据类型是bigint,我在写Entitiy时将它作为long处理: ``` [Column("article_id", TypeName = "bigint")] public long Id { get; set; } ``` 当我Get实体时,能够正常获取到它的id。之后我定义了一个方法 ArticleExistsAsync,希望根据传入的long类型id,判断该实体是否存在: ``` public async Task<bool> ArticleExistsAsync(long articleId) { return await _context.Articles.AnyAsync(x => x.Id==articleId); } ``` 但是在运行时抛出了如下异常 >InvalidOperationException: No coercion operator is defined between types 'System.Int16' and 'System.Boolean'. > System.Linq.Expressions.Expression.GetUserDefinedCoercionOrThrow(ExpressionType coercionType, Expression expression, Type convertToType) 目前没有头绪,希望各位dalao能提供一些解决思路,非常感谢。

C# Socket服务器接收HTTP请求,不能全部做出响应

使用Socket作为服务器,接收HTTP请求,在Socket socket = socketListen.Accept();之后启动一个线程处理接收数据 和发送数据,如果不调用socket.Receive(data);接收客户数据的话,那么客户端(也就是HTTP请求)请求多少次, 服务端的Socket socket = socketListen.Accept();就会被调用多少次,就是能百分百接收到客户端请求, 但是通过socket.Send(head)作为HTTP请求返回数据,HTTP请求那边几乎获取不到返回的数据, 偶尔还是能获取到的,相反,不调用socket.Receive(data);方法,就会出现 比如 HTTP请求了100次, socketListen.Accept();可能就被执行了80次,但是这80次调用socket.Send(head)返回给http的数据,http那边都能获取到服务端返回的数据,注:客户端每次发送的数据很少,代码如下public partial class MainWindow : Window { private Socket socketWatch; private Thread listenThread = null; private bool isRun = false; private int pointer = 0; public MainWindow() { InitializeComponent(); init(); } private void init() { socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socketWatch.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 80)); socketWatch.Listen(10); // 参数表示最多可容纳的等待接受的传入连接数,不包含已经建立连接的 listenThread = new Thread(new ParameterizedThreadStart(run)); listenThread.IsBackground = true; } private void run(Object o) { Socket socketListen = (Socket)o; while (isRun) { Socket socket = socketListen.Accept(); pointer = pointer + 1; Thread thread = new Thread(new ParameterizedThreadStart(task)); thread.IsBackground = true; thread.Start(socket); } } private void bn_start_Click(object sender, RoutedEventArgs e) { isRun = true; bn_start.IsEnabled = false; bn_stop.IsEnabled = true; listenThread.Start(socketWatch); } private void bn_stop_Click(object sender, RoutedEventArgs e) { System.Environment.Exit(0); } private void Window_Closed(object sender, EventArgs e) { System.Environment.Exit(0); } private void task(object o) { Socket socket = (Socket)o; byte[] data = new byte[1024 * 2]; // 浏览器发来的数据 int reciverNumber = socket.Receive(data); string resdata = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + " server request time:" + pointer; byte[] body = Encoding.UTF8.GetBytes(resdata); byte[] head = Encoding.UTF8.GetBytes(@"HTTP/1.1 200 OK Content-Length: " + body.Length + @" Content-Type: text/plain Date: " + string.Format("{0:R}", DateTime.Now) + @" Server: Cftea Web Server " + resdata); socket.Send(head); socket.Shutdown(SocketShutdown.Both); socket.Close(); } } ``` ```

c#异步通信代码错误问题

public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } //vs的这段代码中 ,bool connect_flag的connect_flag报了一个警告错误,变量connect_flag已赋值,但是其值从未使用过。如何修改? public static MODEL.DataSourceVersionQuery BrowseDataSource_QueryVersionData() { MODEL.DataSourceVersionQuery result = new MODEL.DataSourceVersionQuery(); //获取数据包 string strPacket = BrowseDataSource_PrepareVersionPacket(); //向服务端提交查询版本信息 string str = DAL.socket.GetSocketData(strPacket); //DAL.socket.GetSocketData(strPacket) vs报了一个错误,非静态字段、方法或属性DAL.socket.GetSocketData(string)“要求对象引用。如何修改? 还有这个错误![图片说明](https://img-ask.csdn.net/upload/201509/16/1442412249_893824.png) 另外我想把DAL中的socket.cs的 public byte[] bytesReceived { get; set; }这段移动到Model中而不报错要如何修改? DAL中socket完整代码如下: using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> class socket { //Socket public Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public bool SocketConnect() { byte[] bytesReceived = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } /// <summary> /// 异步连接的回调函数 /// </summary> /// <param name="ar"></param> public void ConnectCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); bool connect_flag = false; connect_flag = true; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public void SocketSend(string strSend) { Socket clientSocket; //发送创建套接字 int length = strSend.Length; Byte[] bytesSent = new byte[length]; clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { bytesSent = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 clientSocket.BeginSend(bytesSent, 0, bytesSent.Length, 0, new AsyncCallback(SendCallback), clientSocket); //异步发送数据 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } public void SendCallback(IAsyncResult ar) //发送的回调函数 { ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); } /// <summary> /// Socket接收数据 /// </summary> /// <returns> /// 收到的数据 /// </returns> public string SocketReceive() { string result = ""; try { MemoryStream stream = new MemoryStream(); Byte[] bytesReceived = new Byte[256]; clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), clientSocket); ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public void ReceiveCallback(IAsyncResult ar) { Socket client = (Socket)ar.AsyncState; //获取句柄 int bytesread = client.EndReceive(ar); if (bytesread > 0) { clientSocket.BeginReceive(bytesReceived, 0, bytesReceived.Length, 0, new AsyncCallback(ReceiveCallback), client); string content = Encoding.ASCII.GetString(bytesReceived, 0, bytesReceived.Length); } else { ManualResetEvent readDone = new ManualResetEvent(false); //读信号 readDone.Set(); } } /// <summary> /// Socket通信 /// </summary> /// <param name="strSend"> /// 发送的信息 /// </param> /// <returns> /// 包体的内容 /// </returns> public string GetSocketData(string strSend) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceive(); //获取扩展信息的长度 strExtLength = strResult.Substring(16, 12); int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 strDatas = strResult.Substring(ExtLength + 32); //strDatas = decodedString; } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public string SocketReceiveFile(string FileName) { string result = ""; try { MemoryStream streamPacketLength = new MemoryStream(); Byte[] bytesPacketLength = new Byte[16]; clientSocket.Receive(bytesPacketLength, bytesPacketLength.Length, 0); streamPacketLength.Write(bytesPacketLength, 0, bytesPacketLength.Length); result = System.Text.Encoding.Default.GetString(streamPacketLength.ToArray()); int PacketLength = Convert.ToInt32(result); streamPacketLength.Close(); MemoryStream streamExtLength = new MemoryStream(); Byte[] bytesExtLength = new Byte[12]; clientSocket.Receive(bytesExtLength, bytesExtLength.Length, 0); streamExtLength.Write(bytesExtLength, 0, bytesExtLength.Length); result = System.Text.Encoding.Default.GetString(streamExtLength.ToArray()); int ExtLength = Convert.ToInt32(result); streamExtLength.Close(); MemoryStream streamProtocol = new MemoryStream(); Byte[] bytesProtocol = new Byte[4]; clientSocket.Receive(bytesProtocol, bytesProtocol.Length, 0); streamProtocol.Write(bytesProtocol, 0, bytesProtocol.Length); result = System.Text.Encoding.Default.GetString(streamProtocol.ToArray()); string Protocol = result; streamProtocol.Close(); MemoryStream streamExtInfo = new MemoryStream(); Byte[] bytesExtInfo = new Byte[ExtLength]; clientSocket.Receive(bytesExtInfo, bytesExtInfo.Length, 0); streamExtInfo.Write(bytesExtInfo, 0, bytesExtInfo.Length); result = System.Text.Encoding.Default.GetString(streamExtInfo.ToArray()); byte[] Buffer = Convert.FromBase64String(result); string strExtInfo = UTF8Encoding.UTF8.GetString(Buffer); streamExtInfo.Close(); MODEL.FileTrackQuery ExtInfo = new MODEL.FileTrackQuery(); ExtInfo = JsonConvert.DeserializeObject<MODEL.FileTrackQuery>(strExtInfo); if (ExtInfo.code == "00") { FileInfo fi = new FileInfo(FileName); DirectoryInfo di = fi.Directory; if (!di.Exists) { di.Create(); } FileStream streamPacketInfo = new FileStream(FileName, FileMode.Create); if (PacketLength > 0) { Byte[] bytesPacketInfo = new Byte[PacketLength]; int bytes = 0; do { bytes = clientSocket.Receive(bytesPacketInfo, bytesPacketInfo.Length, 0); streamPacketInfo.Write(bytesPacketInfo, 0, bytes); } while (bytes > 0); } streamPacketInfo.Close(); } clientSocket.Close(); string strLogFile = System.AppDomain.CurrentDomain.BaseDirectory + "debug.txt"; StreamWriter sw = new StreamWriter(strLogFile, true); sw.WriteLine("PacketLength : " + PacketLength.ToString()); sw.WriteLine("ExtLength : " + ExtLength.ToString()); sw.WriteLine("strExtInfo : " + strExtInfo); sw.WriteLine("ExtInfo.code : " + ExtInfo.code); sw.WriteLine("\n------------------------------------------------------------------------\n"); sw.Flush(); sw.Close(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } return result; } public string GetSocketFile(string strSend, string FileName) { string strDatas = ""; string strResult = ""; string strExtLength = ""; try { //Socket连接 SocketConnect(); //发送信息 SocketSend(strSend); //接收服务器的信息 strResult = SocketReceiveFile(FileName); //获取扩展信息的长度 //strExtLength = strResult.Substring(16, 12); //int ExtLength = Convert.ToInt32(strExtLength); //扩展信息,暂不使用 //string strExtInfo = strResult.Substring(32, ExtLength); //获取包体的内容 //strDatas = strResult.Substring(ExtLength + 32); } catch (Exception e) { string strError = ""; strError += "\r\n strResult = " + strResult; strError += "\r\n strExtLength = " + strExtLength; DAL.Common.WriteErrorLog(e, strError); strDatas = ""; } return strDatas; } public byte[] bytesReceived { get; set; } } } MODEL完整代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MODEL { public enum ClientEditionEnum { Enterprise,//企业版 Personal,//个人版 Internal,//内部版 None,//error } /// <summary> /// 授权文件内容 /// </summary> public class AuthorizeFileInfo { public string startTime { get; set; } public string expiryTime { get; set; } public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public AuthorizeFileInfo() { startTime = ""; expiryTime = ""; licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; } } /// <summary> /// 通用返回值 /// </summary> /// public class CommonResult { public string code { get; set; } public string message { get; set; } public CommonResult() { code = ""; message = ""; } } public class EnterpriseConfirmAuthorizeDatas { public string sessionID { get; set; } public EnterpriseConfirmAuthorizeDatas() { sessionID = ""; } } /// <summary> /// 企业版授权校验接口 /// </summary> public class EnterpriseConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public EnterpriseConfirmAuthorizeDatas datas { get; set; } public EnterpriseConfirmAuthorizeResult() { code = ""; message = ""; datas = new EnterpriseConfirmAuthorizeDatas(); } } public class PersonalConfirmAuthorizeDatas { public string sessionID { get; set; } public string licenseInfo { get; set; } public PersonalConfirmAuthorizeDatas() { sessionID = ""; licenseInfo = ""; } } /// <summary> /// 个人版授权校验接口 /// </summary> public class PersonalConfirmAuthorizeResult { public string code { get; set; } public string message { get; set; } public PersonalConfirmAuthorizeDatas datas { get; set; } public PersonalConfirmAuthorizeResult() { code = ""; message = ""; datas = new PersonalConfirmAuthorizeDatas(); } } /// <summary> /// 鉴权信息,每次调用安全接口时使用 /// </summary> public class LicInfo { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string deviceID { get; set; } public string sessionID { get; set; } public LicInfo() { licenseID = ""; licensePassword = ""; terminalID = ""; deviceID = ""; sessionID = ""; } } /// <summary> /// java引擎的参数 /// </summary> public class JavaEngineArg { public string licenseID { get; set; } public string licensePassword { get; set; } public string terminalID { get; set; } public string customName { get; set; } public string customID { get; set; } public string deviceID { get; set; } public JavaEngineArg() { licenseID = ""; licensePassword = ""; terminalID = ""; customName = ""; customID = ""; deviceID = ""; } } /// <summary> /// 用户登录接口(一),非安全接口 /// </summary> /// public class UserInfoUnSafe { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public UserInfoUnSafe() { userID = ""; userName = ""; departmentName = ""; } } public class UserLoginUnSafe { public string code { get; set; } public string message { get; set; } public UserInfoUnSafe datas { get; set; } public UserLoginUnSafe() { code = ""; message = ""; datas = new UserInfoUnSafe(); } } /// <summary> /// 个人版用户登录接口,非安全接口 /// </summary> /// public class UserInfoForPersonal { public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string licenseInfo { get; set; } public UserInfoForPersonal() { userID = ""; userName = ""; departmentName = ""; licenseInfo = ""; } } public class UserLoginForPersonal { public string code { get; set; } public string message { get; set; } public UserInfoForPersonal datas { get; set; } public UserLoginForPersonal() { code = ""; message = ""; datas = new UserInfoForPersonal(); } } /// <summary> /// 用户登录接口(二),安全接口 /// </summary> /// public class UserInfoSafe { public string userSessionID { get; set; } public string userID { get; set; } public string userName { get; set; } public string departmentName { get; set; } public string activeTime { get; set; } public UserInfoSafe() { userSessionID = ""; userID = ""; userName = ""; departmentName = ""; activeTime = ""; } } public class UserLoginSafe { public string code { get; set; } public string message { get; set; } public UserInfoSafe datas { get; set; } public UserLoginSafe() { code = ""; message = ""; datas = new UserInfoSafe(); } } /// <summary> /// 更新检查接口 /// </summary> /// public class SingleVersion { public string softID { get; set; } public int version { get; set; } public SingleVersion() { softID = ""; version = new int(); } } public class Versions { public List<SingleVersion> versions { get; set; } public Versions() { versions = new List<SingleVersion>(); } } public class VersionUpdate { public string softID { get; set; } public int version { get; set; } public string url { get; set; } public VersionUpdate() { softID = ""; version = new int(); url = ""; } } public class VersionCheck { public string code { get; set; } public string message { get; set; } public List<VersionUpdate> datas { get; set; } public VersionCheck() { code = ""; message = ""; datas = new List<VersionUpdate>(); } } /// <summary> /// 数据源信息查询接口 /// </summary> /// public class OptInfoQuery { public string createUserID { get; set; } public string createUserName { get; set; } public string createUserTime { get; set; } public OptInfoQuery() { createUserID = ""; createUserName = ""; createUserTime = ""; } } public class Period { public int cycle { get; set; } public int cycleUnit { get; set; } public string timer { get; set; } public Period() { cycle = 1; cycleUnit = 1; timer = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"); } } public class StrategyConfig { public int backType { get; set; } public int taskType { get; set; } public Period config { get; set; } public StrategyConfig() { backType = 0; taskType = 1; config = new Period(); } } public class FilterFileSuffix { public string suffix { get; set; } public FilterFileSuffix() { suffix = ""; } } public class Scan { public int scanType { get; set; } public string root { get; set; } public bool scanHideFile { get; set; } public string verifyCompleteName { get; set; } public int verifyCompleteMaxCount { get; set; } public int verifyCompleteTimer { get; set; } public string fileAttrGainer { get; set; } public bool recordCanNotReadFileInfo { get; set; } public bool recordEmptyDirectory { get; set; } public bool recordEmptyFile { get; set; } public List<FilterFileSuffix> filterFileSuffix { get; set; } public Scan() { scanType = 2; root = ""; scanHideFile = false; verifyCompleteName = ""; verifyCompleteMaxCount = 5; verifyCompleteTimer = 10000; fileAttrGainer = "null"; recordCanNotReadFileInfo = false; recordEmptyDirectory = false; recordEmptyFile = false; filterFileSuffix = new List<FilterFileSuffix>(); } } public class DataSourceConfigQuery { public int status { get; set; } public int dataSourceType { get; set; } public string dataSourceID { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigQuery() { status = 0; dataSourceType = 0; dataSourceID = ""; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } public class DataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<DatasQuery> datas { get; set; } public DataSourceInfoQuery() { code = ""; message = ""; datas = new List<DatasQuery>(); } } public class WebSite { public string ExpirationTime { get; set; } public string WebSiteSpace { get; set; } public bool DataBaseEnable { get; set; } public string DataBaseUserName { get; set; } public string DataBasePassword { get; set; } public string DataBaseMark { get; set; } public string WebSiteAdmin { get; set; } public string WebSitePassword { get; set; } public WebSite() { ExpirationTime = ""; WebSiteSpace = ""; DataBaseEnable = false; DataBaseUserName = ""; DataBasePassword = ""; DataBaseMark = ""; WebSiteAdmin = ""; WebSitePassword = ""; } } public class WebSiteDatasQuery { public OptInfoQuery optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public WebSite webSiteConfig { get; set; } public WebSiteDatasQuery() { optInfo = new OptInfoQuery(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); webSiteConfig = new WebSite(); } } public class WebSiteDataSourceInfoQuery { public string code { get; set; } public string message { get; set; } public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceInfoQuery() { code = ""; message = ""; datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 新增数据源接口 /// </summary> /// public class OptInfoNew { public bool forceFlag { get; set; } public OptInfoNew() { forceFlag = true; } } public class DataSourceConfigNew { public int dataSourceType { get; set; } public string dataSourceName { get; set; } public string dataSourceDescription { get; set; } public Scan config { get; set; } public DataSourceConfigNew() { dataSourceType = 0; dataSourceName = ""; dataSourceDescription = ""; config = new Scan(); } } public class DataSourceNew { public OptInfoNew optInfo { get; set; } public StrategyConfig strategyConfig { get; set; } public DataSourceConfigNew dataSourceConfig { get; set; } public DataSourceNew() { optInfo = new OptInfoNew(); strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigNew(); } } /// <summary> /// 修改数据源接口 /// </summary> /// public class DataSourceModify { public StrategyConfig strategyConfig { get; set; } public DataSourceConfigQuery dataSourceConfig { get; set; } public DataSourceModify() { strategyConfig = new StrategyConfig(); dataSourceConfig = new DataSourceConfigQuery(); } } /// <summary> /// 停用/启用数据源接口 /// </summary> /// public class DataSourceStatus { public string dataSourceID { get; set; } public int optType { get; set; } public DataSourceStatus() { dataSourceID = ""; optType = new int(); } } /// <summary> /// 数据源数据,仅用于存放数据 /// </summary> /// public class DataSourceData { public List<DatasQuery> datas { get; set; } public DataSourceData() { datas = new List<DatasQuery>(); } } /// <summary> /// WebSite数据源数据,仅用于存放数据 /// </summary> /// public class WebSiteDataSourceData { public List<WebSiteDatasQuery> datas { get; set; } public WebSiteDataSourceData() { datas = new List<WebSiteDatasQuery>(); } } /// <summary> /// 文件恢复,版本查询 /// </summary> /// public class DataSourceVersionArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 前置机编号 public string terminalId { get; set; } // 操作用户编号 public string optUserID { get; set; } public DataSourceVersionArg() { secretKey = ""; token = ""; terminalId = ""; optUserID = ""; } } public class FileVersions { public int file_count { get; set; } public long space_size { get; set; } public string task_id { get; set; } public string task_time { get; set; } public int total_count { get; set; } public string version { get; set; } public FileVersions() { file_count = new int(); space_size = new long(); task_id = ""; task_time = ""; total_count = new int(); version = ""; } } public class DataSourceVersion { public Scan datasourceConfig { get; set; } public string datasourceId { get; set; } public string datasourceName { get; set; } public int datasourceStatus { get; set; } public int datasourceType { get; set; } public List<FileVersions> versions { get; set; } public DataSourceVersion() { datasourceConfig = new Scan(); datasourceId = ""; datasourceName = ""; datasourceStatus = new int(); datasourceType = new int(); versions = new List<FileVersions>(); } } /// <summary> /// 查询数据源接口 /// </summary> public class DataSourceVersionQuery { public string code { get; set; } public string message { get; set; } public List<DataSourceVersion> datas { get; set; } public DataSourceVersionQuery() { code = ""; message = ""; datas = new List<DataSourceVersion>(); } } /// <summary> /// 数据源版本信息 /// </summary> public class DataSourceVersionDatas { public List<DataSourceVersion> datas { get; set; } public DataSourceVersionDatas() { datas = new List<DataSourceVersion>(); } } /// <summary> /// 文件恢复,文件信息查询 /// </summary> /// public class QueryFileInfoArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 数据源编号 public string datasourceId { get; set; } // 操作用户编号 public string optUserID { get; set; } // 目录文件编号--如果为根目录使用 DS_ROOT public string fileID { get; set; } // 查询的版本编号 如果是综合分析 这个字段设置为 ALL public string taskID { get; set; } public QueryFileInfoArg() { secretKey = ""; token = ""; datasourceId = ""; optUserID = ""; fileID = ""; taskID = ""; } } public class FileInfoCondition { public string datasourceId { get; set; } public string parentId { get; set; } public string taskID { get; set; } public FileInfoCondition() { datasourceId = ""; parentId = ""; taskID = ""; } } public class FileInfo { // 文件唯一编号 public string file_id { get; set; } // 源相对目录 public string file_src_path { get; set; } // 文件名 public string file_name { get; set; } // 文件后缀 public string file_suffix { get; set; } // 是否为文件 public bool is_file { get; set; } // 上级文件编号 public string parent_id { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件大小 public int size { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 是否可读 public bool can_read { get; set; } public FileInfo() { file_id = ""; file_src_path = ""; file_name = ""; file_suffix = ""; is_file = new bool(); parent_id = ""; is_del = new bool(); is_hide = new bool(); size = new int(); create_time = ""; create_user = ""; lm_time = ""; lm_user = ""; can_read = new bool(); } } public class FileInfoAndCondition { public FileInfoCondition condition { get; set; } public List<FileInfo> fileInfos { get; set; } public FileInfoAndCondition() { condition = new FileInfoCondition(); fileInfos = new List<FileInfo>(); } } /// <summary> /// 查询文件信息接口 /// </summary> public class FileInfoQuery { public string code { get; set; } public string message { get; set; } public FileInfoAndCondition datas { get; set; } public FileInfoQuery() { code = ""; message = ""; datas = new FileInfoAndCondition(); } } /// <summary> /// 文件信息 /// </summary> public class FileInfoData { public List<FileInfo> datas { get; set; } public FileInfoData() { datas = new List<FileInfo>(); } } public class QueryFileTrackArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 文件编号 public string fileID { get; set; } // 操作用户编号 public string optUserID { get; set; } // 查询的版本编号 public string taskID { get; set; } public QueryFileTrackArg() { secretKey = ""; token = ""; fileID = ""; optUserID = ""; taskID = ""; } } public class FileTrack { // 文件操作 public string act_cmd { get; set; } // 是否可读 public bool can_read { get; set; } // 文件创建时间 public string create_time { get; set; } // 文件创建人 public string create_user { get; set; } // 是否删除 public bool is_del { get; set; } // 是否隐藏 public bool is_hide { get; set; } // 文件最后修改时间 public string lm_time { get; set; } // 文件最后修改人 public string lm_user { get; set; } // 文件大小 public int size { get; set; } public string taskID { get; set; } public FileTrack() { act_cmd = ""; can_read = new bool(); create_time = ""; create_user = ""; is_del = new bool(); is_hide = new bool(); lm_time = ""; lm_user = ""; size = new int(); taskID = ""; } } public class FileTrackCondition { public string fileID { get; set; } public string taskID { get; set; } public FileTrackCondition() { fileID = ""; taskID = ""; } } /// <summary> /// 查询文件轨迹接口 /// </summary> public class FileTrackQuery { public string code { get; set; } public string message { get; set; } public FileTrackCondition condition { get; set; } public List<FileTrack> datas { get; set; } public FileTrackQuery() { code = ""; message = ""; condition = new FileTrackCondition(); datas = new List<FileTrack>(); } } /// <summary> /// 文件轨迹 /// </summary> public class FileTrackData { public List<FileTrack> datas { get; set; } public FileTrackData() { datas = new List<FileTrack>(); } } /// <summary> /// 字典item /// </summary> public class DictionaryData { public string version { get; set; } public string task_time { get; set; } public DictionaryData() { version = ""; task_time = ""; } } public class FileRecoverArg { // 通讯令牌 public string secretKey { get; set; }//由token进过MD5->BASE64->MD5获得 // 任务令牌 public string token { get; set; }//客户端生成一个UUID // 操作用户编号 public string optUserID { get; set; } public string fileID { get; set; } public string taskID { get; set; } public string password { get; set; } public FileRecoverArg() { secretKey = ""; token = ""; optUserID = ""; fileID = ""; taskID = ""; password = ""; } } }

有用过DOTNETTY的朋友嘛,链接错误WaitingForActivation

代码如下: public async void SimpleSend(bool bindClient, IByteBufferAllocator allocator, AddressFamily addressFamily, byte[] expectedData, int count) { var clientGroup = new MultithreadEventLoopGroup(1); var clientBootstrap = new Bootstrap(); clientBootstrap .Group(clientGroup) .ChannelFactory(() => new SocketDatagramChannel(addressFamily)) .Option(ChannelOption.Allocator, allocator) .Option(ChannelOption.SoBroadcast, true) .Option(ChannelOption.IpMulticastLoopDisabled, false) .Handler(new ActionChannelInitializer<IChannel>(channel => { channel.Pipeline.AddLast("Test", new NetUtil.TestHandler()); })); var clientEndPoint = new IPEndPoint( addressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any, IPEndPoint.MinPort); IPAddress add = IPAddress.Parse(this.txtIP.Text); clientBootstrap .LocalAddress(clientEndPoint) .RemoteAddress(new IPEndPoint(add.Address, Int16.Parse(this.txtPort.Text))); Task <IChannel> task = null; if (bindClient) { IPAddress addressLocal = NetUtil.GetLoopbackAddress(addressFamily); task = clientBootstrap.BindAsync(clientEndPoint); //(clientEndPoint); Console.WriteLine(task); Int64 i = 1; while (!task.IsCompleted) { Console.WriteLine(task.Status); //《《==此处“WaitingForActivation” Thread.Sleep(10); } clientChannel = task.Result; Console.WriteLine(task.AsyncState); } else { task = (Task<IChannel>)clientBootstrap.RegisterAsync(); clientChannel = task.Result; }

unity中如何用多线程或者协程解决耗时函数(具有参数和返回值)问题

我在第一个场景中,将很多实时的数据存进了静态列表中,列表的长度有好几千。在第二个场景中定义了一个很复杂的函数(动态事件规整算法,矩阵向量运算)来处理这些数据,这个函数具有参数和返回值。在场景跳转的时候卡顿,需要等好久才能跳到第二个场景。我如果不调用这个函数,场景可以顺利跳转。如何用多线程或者协程来处理具有参数和返回值的耗时函数问题。

socket如何实现其中的发送回调函数和完成发送的代码功能

c#socket异步通信中的SendCallback类包含在静态类中如何实现其中的发送回调函数和完成发送的代码功能 以及错误如何解决![![图片说明](https://img-ask.csdn.net/upload/201509/16/1442378500_213820.jpg)图片说明](https://img-ask.csdn.net/upload/201509/16/1442378441_762401.jpg) using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using System.ComponentModel; using System.Data; using System.Windows.Forms; using System.Threading; namespace DAL { /// <summary> /// Socket接口 /// </summary> static class socket { //Socket public static Socket clientSocket; /// <summary> /// socket连接 /// </summary> /// <returns> /// true 成功 /// false 失败 /// </returns> public static bool SocketConnect() { byte[] receive_buff = new byte[256]; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 ManualResetEvent readDone = new ManualResetEvent(false); //读信号 ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束 //从配置文件获取IP string SocketIP = DAL.Common.ReadConfigString("Recover", "IP"); //从配置文件获取端口 int SocketPort = Convert.ToInt32(DAL.Common.ReadConfigString("Recover", "Port")); //创建IP地址 IPAddress IP = IPAddress.Parse(SocketIP); try { //创建socket实例 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //创建网络端点 IPEndPoint ipEnd = new IPEndPoint(IP, SocketPort); //EndPoint ipEnd = (EndPoint)remotepoint; //与目标终端连接 clientSocket.BeginConnect(ipEnd, new AsyncCallback(ConnectCallback), clientSocket);//调用回调函数 connectDone.WaitOne(); if (clientSocket.Connected) { return true; } else { return false; } } catch (Exception e) { string strError = ""; strError += "\r\n SocketIP = " + SocketIP.ToString(); strError += "\r\n SocketPort = " + SocketPort.ToString(); DAL.Common.WriteErrorLog(e, strError); return false; } } public static void ConnectCallback(IAsyncResult ar) { bool connect_flag = false; ManualResetEvent connectDone = new ManualResetEvent(false); //连接的信号 Socket client = (Socket)ar.AsyncState; client.EndConnect(ar); connect_flag = true; connectDone.Set(); } /// <summary> /// Socket发送数据 /// </summary> /// <param name="strSend"> /// 数据的内容 /// </param> public static void SocketSend(string strSend) { Socket tcpsend; //发送创建套接字 ManualResetEvent sendDone = new ManualResetEvent(false);//发送结束 int length = strSend.Length; Byte[] Bysend = new byte[length]; try { Bysend = System.Text.Encoding.Default.GetBytes(strSend); //将字符串指定到指定Byte数组 tcpsend.BeginSend(Bysend, 0, Bysend.Length, 0, new AsyncCallback(SendCallback), tcpsend); //异步发送数据 sendDone.WaitOne(); } catch (Exception e) { string strError = ""; DAL.Common.WriteErrorLog(e, strError); } } private void SendCallback(IAsyncResult ar) //发送的回调函数 { Socket client = (Socket)ar.AsyncState; int bytesSend = client.EndSend(ar); //完成发送 sendDone.Set(); }![图片说明](https://img-ask.csdn.net/upload/201509/16/1442378304_186857.jpg)

等待多个goroutines的结果

<div class="post-text" itemprop="text"> <p>I am searching a way to execute asynchronously two functions in go which returns different results and errors, wait for them to finish and print both results. Also if one of function returned error I do not want to wait for another function, and just print the error. For example, I have this functions:</p> <pre><code>func methodInt(error bool) (int, error) { &lt;-time.NewTimer(time.Millisecond * 100).C if error { return 0, errors.New("Some error") } else { return 1, nil } } func methodString(error bool) (string, error) { &lt;-time.NewTimer(time.Millisecond * 120).C if error { return "", errors.New("Some error") } else { return "Some result", nil } } </code></pre> <p>Here <a href="https://play.golang.org/p/-8StYapmlg" rel="nofollow noreferrer">https://play.golang.org/p/-8StYapmlg</a> is how I implemented it, but it has too much code I think. It can be simplified by using interface{} but I don't want to go this way. I want something simpler as, for example, can be implemented in C# with async/await. Probably there is some library that simplifies such operation.</p> <p>UPDATE: Thank for your responses! It is awesome how fast I got help! I like the usage of WaitGroup. It obviously makes the code more robust to changes, so I easily can add another async method without changing exact count of methods in the end. However, there is still so much code in comparison to same in C#. I know that in go I don't need to explicitly mark methods as async, making them actually to return tasks, but methods call looks much more simple, for example, consider this link <a href="https://stackoverflow.com/questions/25009437/running-multiple-async-tasks-and-waiting-for-them-all-to-complete">actually catching exception is also needed</a> By the way, I found that in my task I actually don't need to know returning type of the functions I want to run async because it will be anyway marshaled to json, and now I just call multiple services in the endpoint layer of go-kit.</p> </div>

我可以用php / nodejs与SignalR api交谈吗?

<div class="post-text" itemprop="text"> <p>so I'm a PHP and NODEJS programmer, I'm trying to talk to an API </p> <p>the company that provides the API told me they only have <code>c#</code> client and they gave me some c# code and documentation and a link ... I assumed it must be soap or rest API </p> <p>so I open the link and saw this error</p> <pre><code>Protocol error: Unknown transport. </code></pre> <p>so I searched the error and found out its related to <code>SignalR lib</code>, so it must be a <code>SignalR API</code> (I'm guessing ... if that's the right name for it )</p> <p>I also searched for <code>SignalR</code> in the code they gave me and saw this</p> <pre><code>namespace OMS.Business.Client { public abstract class SignalRClientProxyBase : IDisposable { protected HubConnection Connection { get; private set; } protected IHubProxy Hub { get; private set; } public string ServiceUrl { get; private set; } public string HubName { get; private set; } private Task _connectionTask; public string ServerName { get; private set; } public SignalRClientProxyBase(string serverUrl, string hubName, string serverName, bool autoReconnect, Dictionary&lt;string, string&gt; queryString = null) { ServiceUrl = serverUrl; HubName = hubName; ServerName = serverName; if (queryString != null) { Connection = new HubConnection(serverUrl, queryString); } else { Connection = new HubConnection(serverUrl); } if (autoReconnect) { Connection.StateChanged += _connection_StateChanged; } Hub = Connection.CreateHubProxy(hubName); InitHub(Hub); StartConnection(); try { Connection.Start().Wait(); } catch (Exception ex) { /*Nothing*/} } </code></pre> <p>which seems to be confirming my guess </p> <p>so my question is is it possible to talk to this API with PHP or should I give up? basically, I'm in the dark, the company doesn't provide any help .... any suggestion or pointers will be appreciated.</p> </div>

阿贾克斯邮政电话不起作用

<div class="post-text" itemprop="text"> <p>I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code Please figure out that if any problem and also I am not getting any error.</p> <p>url="http://localhost:49917/Account/SaveAddress" </p><div class="snippet" data-lang="js" data-hide="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>this.SaveAddress = function (url, addressData) { $.ajax({ type: "POST", url: url, dataType: "json", data: JSON.stringify(addressData), contentType: 'application/json; charset=utf-8', success: function (responseDetail) { }, error:function(e) { }, }); return 0; };</code></pre> </div> </div> <pre><code>public async Task&lt;ActionResult&gt; SaveAddress(AddressListViewModel addressListVM) { bool response; string message; if (addressListVM.ID &lt;= 0) { response = await Task.Run(() =&gt; AccountManager.Instance().AddAddress(addressListVM)); message = response ? "New address added successfully." : "Failed to add new address."; } else { response = await Task.Run(() =&gt; AccountManager.Instance().UpdateAddress(addressListVM)); message = response ? "Selected address updated successfully." : "Failed to update selected address."; } ModelState.Clear(); return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet); //return PartialView("_AddressDetail", BuildAddressListEntity( // UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true)); } </code></pre> </div>

将图片从xamarin表单上传到php服务器

<div class="post-text" itemprop="text"> <p>Please I have been trying to upload pictures from a xamarin form application to a php server but seems not to be working. The server receives an empty $_FILES request. This is the c# code.</p> <pre><code> public async Task&lt;bool&gt; Upload(MediaFile mediaFile, string filename) { byte[] bitmapData; var stream = new MemoryStream(); mediaFile.GetStream().CopyTo(stream); bitmapData = stream.ToArray(); var fileContent = new ByteArrayContent(bitmapData); fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "fileUpload", FileName = filename }; string boundary = "---8393774hhy37373773"; MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary); multipartContent.Add(fileContent); HttpClient httpClient = new HttpClient(); HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent); response.EnsureSuccessStatusCode(); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); return true; } return false; } </code></pre> <p>Below is the php file to receive the uploaded image. I tried to save the content of the posted image to file but the file only has an empty array and always return "failure". Please what am i missing wrong? I have searched the web but cant seem to understand the problem.</p> <pre><code> $uploads_dir = 'uploads/'; $req_dump = print_r( $_FILES, true ); $fp = file_put_contents( 'data.txt', $req_dump ); if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"])) { $tmp_name = $_FILES["fileUpload"]["tmp_name"]; $name = $_FILES["fileUpload"]["name"]; $Result = move_uploaded_file($tmp_name, "$uploads_dir/$name"); echo "Success"; } else { echo "Failure"; } </code></pre> </div>

启动应用程序时,有没有办法以编程方式清除浏览器缓存?

<div class="post-text" itemprop="text"> <p>由于我对用C#编程(并在WPF中创建应用程序)相当陌生,所以我想寻求您的帮助。</p> <p>我们已经实现了我们称为“JobCacheUpdater”的东西。在不钻研太多细节的情况下,我们的基本想法如下:</p> <ul> <li>1、我们的数据库包含数千个具有不同信息位的项目。</li> <li>2、然后,我们希望异步地在我们的网站上加载这些信息(Ajax)。</li> <li>3、但是,我们不需要将这些信息单独地拼凑在一起,而是要将HTML-字符串呈现到数据库中的一个单独的表中。</li> <li>4、然后,我们根据一个ProjectID从该表中选择一行,该HTML-String基本上显示了包含项目所需信息的表。</li> </ul> <p>这个“JobCacheUpdater”定期运行,这样我们就可以将带有HTML字符串的表与所有项目的主表同步起来。</p> <p>到目前为止,我们已经使用Watin在后台运行浏览器、读取和呈现HTML-字符串,但我目前的任务是实现ChromiumEmbeddedFramework(CEF),而不是实现已有的功能。</p> <p>在示例WPF项目中编写基本代码非常容易,但是当我使用项目的一些随机URL读取该页面的源代码并将其写入.txt文件时,我注意到它只加载了网站的“骨架”(如果我可以这样称呼它),但没有加载包含必要信息的表。</p> <p>我编写了一个ChromeWrapper类,如下所示:</p> <pre><code>public class ChromeWrapper : IDisposable { private readonly ChromiumWebBrowser _browser; private string _html = ""; private bool _pageIsLoaded = false; public ChromeWrapper() { var settings = new CefSettings(); settings.CefCommandLineArgs.Add("disable-gpu", "1"); Cef.Initialize(settings, shutdownOnProcessExit: true, performDependencyCheck: true); _browser = new ChromiumWebBrowser(string.Empty); _browser.BrowserSettings.ApplicationCache = CefState.Disabled; } public string GetHtml(string url) { _pageIsLoaded = false; while (!_browser.IsBrowserInitialized) Thread.Sleep(100); _browser.Load(url); _browser.LoadingStateChanged += BrowserLoadingStateChanged; while (!_pageIsLoaded) Thread.Sleep(100); return _html; } private void BrowserLoadingStateChanged(object sender, LoadingStateChangedEventArgs e) { // Check to see if loading is complete - this event is called twice, one when loading starts // second time when it's finished // (rather than an iframe within the main frame). if (e.IsLoading) return; _browser.LoadingStateChanged -= BrowserLoadingStateChanged; var htmlTask = e.Browser.MainFrame.GetSourceAsync(); htmlTask.ContinueWith(obj =&gt; { _html = htmlTask.Result; _pageIsLoaded = true; }); } public void Dispose() { if (_browser != null) _browser.Dispose(); Cef.Shutdown(); } } </code></pre> <p>单击Button1后,我的MainWindows类实例化ChromeWrapper,然后将源保存到我的桌面上的.txt文件中:</p> <pre><code> private void Button1Click(object sender, RoutedEventArgs e) { using (var chrome = new ChromeWrapper()) { var html = chrome.GetHtml(@"URL Test"); var htmltPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CefSharpTest2.html"); File.WriteAllText(htmltPath, html); Process.Start(htmltPath); chrome.Dispose(); } } </code></pre> <p>有趣的是,如果我在Button1Click中两次启动chrome.GetHtml,就会得到想要的结果,这使我得出结论,浏览器缓存可能有问题,但是我不是很确定。</p> <p>另一个问题:启动应用程序时,有没有办法以编程方式清除浏览器缓存?</p> <p>任何帮助都将不胜感激,谢谢!</p> </div>

测试http.Response.Body已关闭

<div class="post-text" itemprop="text"> <p>I'm searching for an easy way to test that http.Response.Body.Close() was called.</p> <p>I already tried this by counting the number of open connections to the server (<a href="https://golang.org/src/net/http/serve_test.go" rel="nofollow noreferrer">https://golang.org/src/net/http/serve_test.go</a> - countCloseListener), but it seems that it only is testable on the client side, via rewriting the Roundtripper.</p> <p>So the following example works, but I'm wondering whether there is an easier way for such a common task...</p> <pre><code>package closing import "net/http" type MyClient struct { Client http.Client } func (c *MyClient) Closing() (err error) { res, err := c.Client.Get("http://localhost") defer res.Body.Close() return } func (c *MyClient) NotClosing() (err error) { _, err = c.Client.Get("http://localhost") return } </code></pre> <p><a href="https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest.go" rel="nofollow noreferrer">https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest.go</a></p> <pre><code>package closing_test import ( "github.com/elgohr/closing" "io" "io/ioutil" "net/http" "strings" "testing" ) func TestShouldBeClosedWhenClosed(t *testing.T) { tripper := NewFakeRoundTripper() cl := closing.MyClient{ Client: http.Client{ Transport: tripper, }, } if err := cl.Closing(); err != nil { t.Error(err) } if !tripper.Body.Closed { t.Error("Should be closed, but wasn't") } } func TestShouldBeOpenWhenNotClosed(t *testing.T) { tripper := NewFakeRoundTripper() cl := closing.MyClient{ Client: http.Client{ Transport: tripper, }, } if err := cl.NotClosing(); err != nil { t.Error(err) } if tripper.Body.Closed { t.Error("Should be open, but wasn't") } } func NewFakeRoundTripper() *FakeRoundTripper { return &amp;FakeRoundTripper{ Body: &amp;FakeReadCloser{ ReadCloser: ioutil.NopCloser(strings.NewReader("content")), }, } } type FakeRoundTripper struct { Body *FakeReadCloser } func (r *FakeRoundTripper) RoundTrip(*http.Request) (*http.Response, error) { return &amp;http.Response{ Body: r.Body, }, nil } type FakeReadCloser struct { io.ReadCloser Closed bool } func (r *FakeReadCloser) Close() error { r.Closed = true return r.ReadCloser.Close() } </code></pre> <p><a href="https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest_test.go" rel="nofollow noreferrer">https://github.com/elgohr/golang-test-body-close/blob/master/performsHttpRequest_test.go</a></p> </div>

尝试将图像(以字节[]形式发送)上传到PHP中的域文件夹/服务器

<div class="post-text" itemprop="text"> <p>With this current code when I send a byte [] (and the imagename) from my frontend I receive this echo in the log "upload failed". I have an existing folder on my domain named "photosFolder" where I try to store my image and its imagename that I send from the frontend.</p> <p>I am a bit confused now how to make this work so I added an move_uploaded_file that I frequently saw when I googled this issue. Is that the correct approach?</p> <p>This is the PHP-code that I currently have.</p> <pre><code>&lt;?php $input = file_get_contents('php://input'); $value = json_decode($input, true); if (!empty($value)) { file_put_contents($value['photo_name'], base64_decode($value['photo_data'])); $image_name = $value['photo_name']; $image_data = $value['photo_data']; if(move_uploaded_file($image_data, "photosFolder/$image_name")) { echo "image uploaded!"; } else { echo "upload failed"; } } ?&gt; </code></pre> <p>I send my byte [] like this from my frontend:</p> <pre><code>static public async Task&lt;bool&gt; createPhotoThree(string imgName, byte[] imgData) { var httpClientRequest = new HttpClient(); var postData = new Dictionary&lt;string, object&gt;(); postData.Add("photo_name", imgName); postData.Add("photo_data", imgData); var jsonRequest = JsonConvert.SerializeObject(postData); HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json"); var result = await httpClientRequest.PostAsync("http://myadress.com/test.php", content); var resultString = await result.Content.ReadAsStringAsync(); return true; } </code></pre> </div>

如何从PHP中的byte []获取image_name和image_tmp_name?

<div class="post-text" itemprop="text"> <p>I am currently sending an byte [] from my frontend into my domain and PHP-code. The byte array that I am sending is named "photo" and it is sent like a System.Text.Encoding.UTF8, "application/json". My goal is to get the byte [] into an image and then upload it my domainfolder (that already exists) do I need to get the image_name and the image_tmp_name from that byte [] in order to do this? I am a bit uncertain on how exactly I should get this to work.</p> <p>I currently have this code:</p> <pre><code>&lt;?php $value = json_decode(file_get_contents('php://input')); if(!empty($value)) { print_r($value); } ?&gt; </code></pre> <p>With this code the print gives me a huge line of text containing the byte []. </p> <p>How do I now get the image_name and image_tmp_name from this byte []? My goal is to upload the image on my domainmap (named photoFolder that already exists) with a code looking something like this:</p> <pre><code>$image_tmp_name = ""; //I currently do not have this value $image_name = ""; //I currently do not have this value if(move_uploaded_file($image_tmp_name, "photoFolder/$image_name")) { echo "image successfully uploaded"; } </code></pre> <p>How i send it:</p> <pre><code>static public async Task &lt;bool&gt; createPhotoThree (byte [] imgData) { var httpClientRequest = new HttpClient (); var postData = new Dictionary &lt;string, object&gt; (); postData.Add ("photo", imgData); var jsonRequest = JsonConvert.SerializeObject(postData); HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json"); var result = await httpClientRequest.PostAsync("http://myadress.com/test.php", content); var resultString = await result.Content.ReadAsStringAsync (); return true; } </code></pre> </div>

Gorilla Websocket没有收到消息

<div class="post-text" itemprop="text"> <p>I am building a gateway in Golang that communicates with Gorilla websockets.</p> <p>I am running it on Ubuntu 16.04, and testing it currently with a .NET console app.</p> <p>Using Wireshark on Windows and sniffit on Ubuntu have determined that <em>messages are being sent correctly from the Windows client and received by the Ubuntu box</em>.</p> <p>In my code, however, sometimes after a few successful messages, and sometimes after none, my gateway is failing to read the message (still sitting at <code>_, msg, errCon := conn.ReadMessage()</code>)</p> <p>An example of the output will be:</p> <blockquote> <p>2018/03/27 02:38:06 Awaiting Message ... 2018/03/27 02:38:07 Message received: main.AdminRequest{Data:"{\"SomeDataHeader\":\"SomeData\"}", Requestor:"user", Type:"JustDoSomethingRequest", Ukey:"talca"} 2018/03/27 02:38:07 {"SomeDataHeader":"SomeData"} 2018/03/27 02:38:07 Awaiting Message ...</p> </blockquote> <p>As I have previously said, it may receive a few messages like this, but, despite network traffic on both ends continuing, no more messages will be received</p> <p>I am fairly new with Golang, and working under the assumption that I am missing something.</p> <p><strike>I have trimmed out error handling and the like for the sake of brevity in the code below, but this is an example of the failing code.</strike></p> <p><strong>EDIT</strong> As requested I have added Golang full code, and C# client code below (although, as I stated, Wireshark and sniffit have determined that data is going over the wire)</p> <pre><code>package main import ( "fmt" "net/http" "github.com/gorilla/websocket" "encoding/json" "log" ) var upgrader = websocket.Upgrader{ ReadBufferSize: 1024, WriteBufferSize: 1024, CheckOrigin: func(r *http.Request) bool { return true }, } type AdminRequest struct { Data string `json:"Data"` Requestor string `json:"Requestor"` Type string `json:"Type"` Ukey string `json:"Ukey"` } func main() { http.HandleFunc("/a", func(w http.ResponseWriter, r *http.Request) { var conn, _ = upgrader.Upgrade(w, r, nil) go func(conn *websocket.Conn) { for { _, _, err := conn.ReadMessage() if err != nil { log.Println("Close: "+ err.Error()) conn.Close() return } } }(conn) go func(conn *websocket.Conn) { for { log.Println("Awaiting Message ...") _, msg, errCon := conn.ReadMessage() if errCon != nil { log.Println("Read Error:", errCon) break } log.Println("Message received: ") var r AdminRequest if err := json.Unmarshal(msg, &amp;r); err != nil { log.Println("Error: " + err.Error()); return; } fmt.Printf("%#v ", r) log.Println(r.Data); } }(conn) }) http.ListenAndServe(":3000", nil) } </code></pre> <p>C# Code:</p> <pre><code>public class Client : IDisposable { private ClientWebSocket _socket; string _address; int _port; public Client(string address) { _address = address; _socket = new ClientWebSocket(); } public async void SetupForReceivingStuffs() { while (_socket.State == WebSocketState.Open) { ArraySegment&lt;byte&gt; receivedBytes = new ArraySegment&lt;byte&gt;(new byte[1024]); WebSocketReceiveResult result = await _socket.ReceiveAsync(receivedBytes, CancellationToken.None); Console.WriteLine(Encoding.UTF8.GetString(receivedBytes.Array, 0, result.Count)); } } public async void SetupForSendingStuffs(ConcurrentQueue&lt;AdminRequest&gt; queue) { while (_socket.State == WebSocketState.Open) { AdminRequest next; while (queue.Count &gt; 0) { if (queue.TryDequeue(out next)) { await Send(next); } } await Task.Yield(); } } public async Task Connect() { while (_socket.State != WebSocketState.Open) { try { _socket = new ClientWebSocket(); await _socket.ConnectAsync(new Uri(_address), CancellationToken.None); Console.WriteLine("Socket state: " + _socket.State); } catch (Exception ex) { //Not getting hit Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); } } } public Task Send&lt;TData&gt;(TData data) { string text = JsonConvert.SerializeObject(data); var encoded = Encoding.UTF8.GetBytes(text); var buffer = new ArraySegment&lt;Byte&gt;(encoded, 0, encoded.Length); return _socket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } public void Dispose() { _socket.Dispose(); } } </code></pre> <p>Called by:</p> <pre><code>class Program { static ConcurrentQueue&lt;AdminRequest&gt; _toSend; static void Main(string[] args) { _toSend = new ConcurrentQueue&lt;AdminRequest&gt;(); Client client = new Client("ws:/(myip):(myport)/a"); client.Connect().Wait(); //client.SetupForReceivingStuffs(); client.SetupForSendingStuffs(_toSend); WriteInstructions(); LoopAuto(); Console.WriteLine("Bye"); } private static void LoopAuto() { DateTime nextMessage = DateTime.Now; while (true) { if (DateTime.Now &lt; nextMessage) continue; Console.WriteLine("Next"); nextMessage = DateTime.Now.AddSeconds(2); _toSend.Enqueue(new AdminRequest { Data = "{\"SomeDataHeader\":\"SomeData\"}", Requestor = "user", Type = "JustDoSomethingRequest", Ukey = "talca" }); } } private static ConsoleKeyInfo LoopManual() { ConsoleKeyInfo info; do { info = Console.ReadKey(true); if (info.KeyChar == '1') { _toSend.Enqueue(new AdminRequest { Data = "{\"SomeDataHeader\":\"SomeData\"}", Requestor = "user", Type = "JustDoSomethingRequest", Ukey = "talca" }); } else if (info.KeyChar == 'i') { WriteInstructions(); } } while (info.KeyChar != 'x'); return info; } private static void WriteInstructions() { Console.WriteLine("1. Send New Message"); Console.WriteLine("i. Instructions (these lines)"); Console.WriteLine("x: Exit"); } } </code></pre> </div>

软件测试入门、SQL、性能测试、测试管理工具

软件测试2小时入门,让您快速了解软件测试基本知识,有系统的了解; SQL一小时,让您快速理解和掌握SQL基本语法 jmeter性能测试 ,让您快速了解主流来源性能测试工具jmeter 测试管理工具-禅道,让您快速学会禅道的使用,学会测试项目、用例、缺陷的管理、

计算机组成原理实验教程

西北工业大学计算机组成原理实验课唐都仪器实验帮助,同实验指导书。分为运算器,存储器,控制器,模型计算机,输入输出系统5个章节

Java 最常见的 200+ 面试题:面试必备

这份面试清单是从我 2015 年做了 TeamLeader 之后开始收集的,一方面是给公司招聘用,另一方面是想用它来挖掘在 Java 技术栈中,还有那些知识点是我不知道的,我想找到这些技术盲点,然后修复它,以此来提高自己的技术水平。虽然我是从 2009 年就开始参加编程工作了,但我依旧觉得自己现在要学的东西很多,并且学习这些知识,让我很有成就感和满足感,那所以何乐而不为呢? 说回面试的事,这份面试...

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

玩转Python-Python3基础入门

总课时80+,提供源码和相关资料 本课程从Python零基础到纯Python项目实战。内容详细,案例丰富,覆盖了Python知识的方方面面,学完后不仅对Python知识有个系统化的了解,让你从Python小白变编程大牛! 课程包含: 1.python安装 2.变量、数据类型和运算符 3.选择结构 4.循环结构 5.函数和模块 6.文件读写 7.了解面向对象 8.异常处理

程序员的兼职技能课

获取讲师答疑方式: 在付费视频第一节(触摸命令_ALL)片头有二维码及加群流程介绍 限时福利 原价99元,今日仅需39元!购课添加小助手(微信号:csdn590)按提示还可领取价值800元的编程大礼包! 讲师介绍: 苏奕嘉&nbsp;前阿里UC项目工程师 脚本开发平台官方认证满级(六级)开发者。 我将如何教会你通过【定制脚本】赚到你人生的第一桶金? 零基础程序定制脚本开发课程,是完全针对零脚本开发经验的小白而设计,课程内容共分为3大阶段: ①前期将带你掌握Q开发语言和界面交互开发能力; ②中期通过实战来制作有具体需求的定制脚本; ③后期将解锁脚本的更高阶玩法,打通任督二脉; ④应用定制脚本合法赚取额外收入的完整经验分享,带你通过程序定制脚本开发这项副业,赚取到你的第一桶金!

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

基于VHDL的16位ALU简易设计

基于VHDL的16位ALU简易设计,可完成基本的加减、带进位加减、或、与等运算。

MFC一站式终极全套课程包

该套餐共包含从C小白到C++到MFC的全部课程,整套学下来绝对成为一名C++大牛!!!

利用Verilog实现数字秒表(基本逻辑设计分频器练习)

设置复位开关。当按下复位开关时,秒表清零并做好计时准备。在任何情况下只要按下复位开关,秒表都要无条件地进行复位操作,即使是在计时过程中也要无条件地进行清零操作。 设置启/停开关。当按下启/停开关后,将

董付国老师Python全栈学习优惠套餐

购买套餐的朋友可以关注微信公众号“Python小屋”,上传付款截图,然后领取董老师任意图书1本。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

计算机操作系统 第三版.pdf

计算机操作系统 第三版 本书全面介绍了计算机系统中的一个重要软件——操作系统(OS),本书是第三版,对2001年出版的修订版的各章内容均作了较多的修改,基本上能反映当前操作系统发展的现状,但章节名称基

技术大佬:我去,你写的 switch 语句也太老土了吧

昨天早上通过远程的方式 review 了两名新来同事的代码,大部分代码都写得很漂亮,严谨的同时注释也很到位,这令我非常满意。但当我看到他们当中有一个人写的 switch 语句时,还是忍不住破口大骂:“我擦,小王,你丫写的 switch 语句也太老土了吧!” 来看看小王写的代码吧,看完不要骂我装逼啊。 private static String createPlayer(PlayerTypes p...

Vue.js 2.0之全家桶系列视频课程

基于新的Vue.js 2.3版本, 目前新全的Vue.js教学视频,让你少走弯路,直达技术前沿! 1. 包含Vue.js全家桶(vue.js、vue-router、axios、vuex、vue-cli、webpack、ElementUI等) 2. 采用笔记+代码案例的形式讲解,通俗易懂

微信公众平台开发入门

本套课程的设计完全是为初学者量身打造,课程内容由浅入深,课程讲解通俗易懂,代码实现简洁清晰。通过本课程的学习,学员能够入门微信公众平台开发,能够胜任企业级的订阅号、服务号、企业号的应用开发工作。 通过本课程的学习,学员能够对微信公众平台有一个清晰的、系统性的认识。例如,公众号是什么,它有什么特点,它能做什么,怎么开发公众号。 其次,通过本课程的学习,学员能够掌握微信公众平台开发的方法、技术和应用实现。例如,开发者文档怎么看,开发环境怎么搭建,基本的消息交互如何实现,常用的方法技巧有哪些,真实应用怎么开发。

150讲轻松搞定Python网络爬虫

【为什么学爬虫?】 &nbsp; &nbsp; &nbsp; &nbsp;1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到! &nbsp; &nbsp; &nbsp; &nbsp;2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站 【课程设计】 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是: 网络请求:模拟浏览器的行为从网上抓取数据。 数据解析:将请求下来的数据进行过滤,提取我们想要的数据。 数据存储:将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是: 爬虫进阶:包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 Scrapy和分布式爬虫:Scrapy框架、Scrapy-redis组件、分布式爬虫等。 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 &nbsp; 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! 【课程服务】 专属付费社群+每周三讨论会+1v1答疑

SEIR课程设计源码与相关城市数据.rar

SEIR结合学报与之前博客结合所做的一些改进,选择其中三个城市进行拟合仿真SEIR结合学报与之前博客结合所做的一些改进,选择其中三个城市进行拟合仿真SEIR结合学报与之前博客结合所做的一些改进,选择其

Python数据挖掘简易入门

&nbsp; &nbsp; &nbsp; &nbsp; 本课程为Python数据挖掘方向的入门课程,课程主要以真实数据为基础,详细介绍数据挖掘入门的流程和使用Python实现pandas与numpy在数据挖掘方向的运用,并深入学习如何运用scikit-learn调用常用的数据挖掘算法解决数据挖掘问题,为进一步深入学习数据挖掘打下扎实的基础。

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

定量遥感中文版 梁顺林著 范闻捷译

这是梁顺林的定量遥感的中文版,由范闻捷等翻译的,是电子版PDF,解决了大家看英文费时费事的问题,希望大家下载看看,一定会有帮助的

GIS程序设计教程 基于ArcGIS Engine的C#开发实例

张丰,杜震洪,刘仁义编著.GIS程序设计教程 基于ArcGIS Engine的C#开发实例.浙江大学出版社,2012.05

人工智能-计算机视觉实战之路(必备算法+深度学习+项目实战)

系列课程主要分为3大阶段:(1)首先掌握计算机视觉必备算法原理,结合Opencv进行学习与练手,通过实际视项目进行案例应用展示。(2)进军当下最火的深度学习进行视觉任务实战,掌握深度学习中必备算法原理与网络模型架构。(3)结合经典深度学习框架与实战项目进行实战,基于真实数据集展开业务分析与建模实战。整体风格通俗易懂,项目驱动学习与就业面试。 建议同学们按照下列顺序来进行学习:1.Python入门视频课程 2.Opencv计算机视觉实战(Python版) 3.深度学习框架-PyTorch实战/人工智能框架实战精讲:Keras项目 4.Python-深度学习-物体检测实战 5.后续实战课程按照自己喜好选择就可以

三个项目玩转深度学习(附1G源码)

从事大数据与人工智能开发与实践约十年,钱老师亲自见证了大数据行业的发展与人工智能的从冷到热。事实证明,计算机技术的发展,算力突破,海量数据,机器人技术等,开启了第四次工业革命的序章。深度学习图像分类一直是人工智能的经典任务,是智慧零售、安防、无人驾驶等机器视觉应用领域的核心技术之一,掌握图像分类技术是机器视觉学习的重中之重。针对现有线上学习的特点与实际需求,我们开发了人工智能案例实战系列课程。打造:以项目案例实践为驱动的课程学习方式,覆盖了智能零售,智慧交通等常见领域,通过基础学习、项目案例实践、社群答疑,三维立体的方式,打造最好的学习效果。

微信小程序开发实战之番茄时钟开发

微信小程序番茄时钟视频教程,本课程将带着各位学员开发一个小程序初级实战类项目,针对只看过官方文档而又无从下手的开发者来说,可以作为一个较好的练手项目,对于有小程序开发经验的开发者而言,可以更好加深对小程序各类组件和API 的理解,为更深层次高难度的项目做铺垫。

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

去除异常值matlab程序

数据预处理中去除异常值的程序,matlab写成

用verilog HDL语言编写的秒表

在秒表设计中,分模块书写。用在七段数码管上显示。输入频率是1KHZ.可以显示百分秒,秒,分。如要显示小时,只需修改leds里的代码和主模块代码。改程序以通过硬件电路验证。完全正确。

[透视java——反编译、修补和逆向工程技术]源代码

源代码。

相关热词 c# 不能序列化继承类 c# char* 调用 c# 开发dll模板 c#添加控件到工具箱 c#控制台组合数 编程计算猴子吃桃问题c# c# wpf 背景透明 随机抽取号码软件c# c# 开发环境 c# 属性和字段
立即提问