コード例 #1
0
        /// <summary>
        /// 接收消息
        /// </summary>
        public void ReceiveMsg()
        {
            while (true)
            {
                try
                {
                    //接收数据
                    byte[] buffer   = new byte[2048];
                    int    recCount = 0;
                    memStream = new MemoryStream();
                    //接收返回的字节流

                    /*while ((recCount = clientSocket.Receive(buffer)) > 0)
                     * {
                     *  memStream.Write(buffer, 0, recCount);
                     * }*/
                    recCount = clientSocket.Receive(buffer);
                    if (recCount > 0)
                    {
                        returnMsg = Encoding.UTF8.GetString(buffer, 0, recCount);
                        //returnMsg = Encoding.UTF8.GetString(memStream.GetBuffer(), 0, memStream.GetBuffer().Length);
                    }

                    ShowMsg(returnMsg + "\r\n");
                    MsgJson msg = JsonConvert.DeserializeObject <MsgJson>(returnMsg);

                    ShowMsg(string.Format("tasknum:{0};action:{1};context:{2} \r\n", msg.tasknum, msg.action, msg.context));
                }
                catch (Exception ex)
                {
                    ShowMsg("error:" + ex.Message + "\r\n\r\n");
                    break;
                }
            }
        }
コード例 #2
0
        /// <summary>
        /// 发送
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_send_Click(object sender, EventArgs e)
        {
            //客户端给服务器发消息
            if (clientSocket != null)
            {
                try
                {
                    var msgjson = new MsgJson
                    {
                        action  = "0",
                        tasknum = "0",
                        context = "192168002132001"
                    };
                    var strJson = JsonConvert.SerializeObject(msgjson);

                    byte[] buffer = Encoding.UTF8.GetBytes(strJson);
                    clientSocket.Send(buffer);
                }
                catch (Exception ex)
                {
                    ShowMsg("error:" + ex.Message + "\r\n\r\n");
                }
            }
        }