Delphi socket连接.net Socket

在Delphi中使用TclientSocket连接.NET Socket服务时,遇到发送前4字节数字和后续自定义字符串的问题。动态数组array of byte通过socket缓冲区时数据混乱,导致服务端解码错误。通过使用静态数组array [1..5] of byte解决了数据混乱的问题,但应对动态长度数据时仍不适用。最终解决方案是将所有指令和数据转化为字符串,由服务端接收后先解码再解析指令。
摘要由CSDN通过智能技术生成

这几天一直研究Delphi连接.net的socket程序,终于有一些进展。

需求:

服务端截取前4个字节,转换为数字,次数字为业务代码。将决定调用哪个业务逻辑。

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using PivasUpdate;
using log4net;
using System.Reflection;
using System.Net;

namespace PivasUpdate
{

    public class ServiceProcess
    {
        private const int LENGTH=1024;

        private const int GETVERSION = 1;
        private const int DOWNLOADNEW = 2;
        private const int DOWNLOADFILE = 3;

        public static AutoResetEvent allDone = new AutoResetEvent(false);
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private string cliendAddres;
        private string INSTALLPATH = ConfigUtils.GetWindowsServiceInstallPath(ConfigUtils.SERVICENAME);

        public void ProcessCallback(IAsyncResult ar)
        {
            Socket handler = null;
            try
            {

                StateObject state = (StateObject)ar.AsyncState;
                handler = state.workSocket;
                cliendAddres = IPAddress.Parse(((IPEndPoint)handler.RemoteEndPoint).Address.ToString()) + ":"
                + ((IPEndPoint)handler.RemoteEndPoint).Port.ToString() + ":";

                int bytesRead = handler.EndReceive(ar);
                log.Info(cliendAddres + "接受到数据包大小:" + bytesRead + "字节");


                int control = BitConverter.ToInt32(state.buffer, 0);

                string c = UTF8Encoding.UTF8.GetString(state.buffer, 4, bytesRead - 4);

                switch (control)
                {
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值