Socket编程:客户端按照对方定义的协议(包头用16进制)如何发送、接收数据?(200分)

  • 主题发起人 主题发起人 weyoung
  • 开始时间 开始时间
W

weyoung

Unregistered / Unconfirmed
GUEST, unregistred user!
服务端是Java写的,约定的通信协议如下:
ushOrgMachineID(2) | ushOrgCommPort(2) | ushDestMachineID(2) | ushDestCommPort | ushPacketLength | ushCheckSum | xml content
说明:
1. 发送端主机编码|发送端通信端口号|接收端主机编码|接收端通信端口号|xml包体的长度|校验码|xml包体的内容
2. 弧内为字节数,帧内容为文本格式,其它为16进制格式

以下是我写的客户端代码:

unit ClientMain;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, IdAntiFreezeBase, IdAntiFreeze,
IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient;

//这里定义了一个结构,对应于通信协议
type
TMyPack = packed Record
OrgID:Word;
OrgPort:Word;
DestID:Word;
DestPort:Word;
PackLen:Word;
CheckSum:Word;
Body:Array[0..255] of Char;
end;

type
TfrmClient = class(TForm)
Label1: TLabel;
Label2: TLabel;
edHost: TEdit;
edPort: TEdit;
btnConnect: TBitBtn;
btnDisConnect: TBitBtn;
Label3: TLabel;
memSend: TMemo;
btnSend: TBitBtn;
Memo2: TMemo;
IdTCPClient1: TIdTCPClient;
IdAntiFreeze1: TIdAntiFreeze;
procedure btnConnectClick(Sender: TObject);
procedure btnDisConnectClick(Sender: TObject);
procedure IdTCPClient1Connected(Sender: TObject);
procedure btnSendClick(Sender: TObject);
private
fSockConnected: Boolean;
procedure SetSockConnected(const Value: Boolean);

Procedure Lg(Msg:String);
{ Private declarations }
public
{ Public declarations }
Property SockConnected:Boolean Read fSockConnected Write SetSockConnected;
end;

var
frmClient: TfrmClient;

implementation

{$R *.dfm}
//这里进行一些IP、端口设置、连接到对方的代码都省略。

//发送
procedure TfrmClient.btnSendClick(Sender: TObject);
Var
sBody:String;
myPack:^TMyPack;
begin
sBody := Trim(memSend.Text);
Lg('Send To Server:'+sBody);

New(myPack);
myPack.OrgID := 1;
myPack.OrgPort := 1;
myPack.DestID := 1;
myPack.DestPort := 1;
myPack.PackLen := Length(sBody);
myPack.CheckSum := 1;
strpcopy(myPack.Body,sBody);

Try
IdTCPClient1.WriteBuffer(myPack,SizeOf(myPack));
Finally
if myPack <> nil then
begin
FreeMem(myPack,SizeOf(myPack));
end;
end;
end;

end.

现在的问题是服务端收到消息后,解析出来的数据不对。
好象我传过去的包头的内容不对,服务端只读取了ushOrgMachineID和OriginPort,其中OriginID=25292,OriginPort=206,其它的没读到。
请各位帮忙看看
 
// IdTCPClient1.WriteBuffer(myPack,SizeOf(myPack));
上面这句考虑一下,你的大小应该是SIZEOF(TMYPACK)。
试试吧,这个我做过问题不大!!
 
经过咨询朋友后,问题已经搞定。谢谢leaber
 
后退
顶部