alazhuabc304
2015-09-17 14:03
采纳率: 0%
浏览 2.0k

c# socket同步操作代码改异步操作,客户端界面错误问题

c# socket同步操作代码改异步操作,客户端软件界面错误如下:一点击数据源配置模块,就提示数据解析错误,请重启客户端。除了首页模块是正确的以外,点击文件修复和授权信息界面信息都出不来,而且软件卡死,按右上角的关闭键也无法退出。项目采用.net三层架构,修改后的socket类的异步传输部代码如下:

![图片说明](https://img-ask.csdn.net/upload/201509/17/1442497613_763975.png)图片说明
![![![![![![![![![![图片说明](https://img-ask.csdn.net/upload/201509/17/1442498556_560286.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498594_534760.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498557_279873.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498469_791285.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498420_801626.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498378_653933.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498306_209580.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498276_400425.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498211_949856.png)图片说明](https://img-ask.csdn.net/upload/201509/17/1442498103_147396.png)图片说明

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

9条回答 默认 最新

  • blownewbee 2015-09-17 22:32

    图太小,代码不全,你跳出的这个错误框的代码在哪里。

    点赞 评论
  • alazhuabc304 2015-09-18 00:34

    public static 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;
            }
        }
    
    点赞 评论
  • alazhuabc304 2015-09-18 00:35
        /// 异步连接的回调函数
    
        /// </summary>
    
        /// <param name="ar"></param>
        public static 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();
        }
    
    点赞 评论
  • alazhuabc304 2015-09-18 00:36

    ///
    /// Socket发送数据
    ///
    ///
    /// 数据的内容
    ///
    public static 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);
            }
        }
    
    点赞 评论
  • alazhuabc304 2015-09-18 00:36

    public static void ReceiveCallback(IAsyncResult ar)
    {
    Socket client = (Socket)ar.AsyncState; //获取句柄
    byte[] bytesReceived = new byte[256];
    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 static 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;
        }
    
    点赞 评论
  • alazhuabc304 2015-09-18 00:37

    public static void SendCallback(IAsyncResult ar) //发送的回调函数
    {
    ManualResetEvent sendDone = new ManualResetEvent(false); //发送结束
    Socket client = (Socket)ar.AsyncState;
    int bytesSend = client.EndSend(ar); //完成发送
    sendDone.Set();
    }
    ///
    /// Socket接收数据
    ///
    ///
    /// 收到的数据
    ///
    public static string SocketReceive()
    {
    string result = string.Empty;
    // 接收缓冲区
    byte[] buffer = new byte[1024];
    // 开始异步接收
    IAsyncResult iar = clientSocket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, null, null);

                // 等待异步接收操作结束 
            iar.AsyncWaitHandle.WaitOne();
    
            // 处理接收操作 
            try
            {
                int byteReceived = clientSocket.EndReceive(iar);
                if (byteReceived > 0)
                {
                    result = Encoding.UTF8.GetString(buffer, 0, byteReceived);
                }
            }
            catch (Exception e)
            {
                string strError = e.Message;
                DAL.Common.WriteErrorLog(e, strError);
            }
            finally
            {
                clientSocket.Close();
            } 
             return result;
        }
    
    点赞 评论
  • alazhuabc304 2015-09-18 00:38

    public static 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;
        }
    
    点赞 评论
  • alazhuabc304 2015-09-18 00:38

    public static 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;
    }

    }
    

    }

    点赞 评论
  • alazhuabc304 2015-09-18 00:39

    socket异步操作的代码都在上面了,大神们帮忙看看啊!

    点赞 评论

相关推荐 更多相似问题