TNMUDP控件接收数据时为什么会有乱码?? (30分)

  • 主题发起人 linshengcd
  • 开始时间
L

linshengcd

Unregistered / Unconfirmed
GUEST, unregistred user!
[?]TNMUDP控件接收数据时为什么会有乱码??(其它简单的代码省去了)代码如下:
点发送按钮:
procedure TForm1.Button1Click(Sender: TObject);
var txt:pchar;
begin
if memo1.Text ='' then
begin
statusbar1.SimpleText :='null to send!';
exit;
end;
GetMem(txt,length(memo1.Text)+1);
Zeromemory(txt,length(memo1.Text )+1);
txt:=pchar(memo1.Text );
nmudp1.SendBuffer(txt^,length(memo1.Text ));
end;
接收时:
procedure TForm1.NMUDP1DataReceived(Sender: TComponent;
NumberBytes: Integer; FromIP: String; Port: Integer);
var txt:pchar;
count:integer;
begin
statusbar1.SimpleText :='receving data';
getmem(txt,numberbytes+1);
zeromemory(txt,numberbytes+1);
nmudp1.ReadBuffer(txt^,count);
memo2.Lines.Add('À´×Ô:'+FromIP+'¶Ë¿Ú:'+inttostr(port)+'ÄÚÈÝΪ:'+txt);
freemem(txt);
statusbar1.SimpleText :='data received';
end;
当字符大于5或6个时,后面的数据就成了乱码,IT同胞们指点.
 
接收缓冲区定义大小
 
getmem(txt,numberbytes+1);大小应该没有问题吧??????
 
numberbytes改到10K
 
张兄,numberbytes是好像不能改变的吧,而且改了好象也没有解决呀
 
你用buf:array[1..10240]of Char;来保存数据
 
:(
对不起,我不会
 
嘻嘻,pipi.出马,一招搞掂
txt:=pchar(memo1.Text );这句是不对的
改成:StrCopy(txt,PChar(memo1.Text))
 
另外,你的发送实在罗嗦,改成下面的吧
---------------------------------------
var s:String;
s:=memo1.text;
nmudp1.SendBuffer(PChar(s)^,length(s));
-----------------------------------------
至于
为什么不用nmudp1.SendBuffer(PChar(memo1.text)^,length(memo1.text));
主要是考虑到上面出现了两次memo1.text。如果没有后面的length(memo1.text)倒是可以的,
所以要多一个s中间变量
 
我记得好象nmudp1有个DATA属性可用
 
更正,可以使用 nmudp1.SendBuffer(PChar(memo1.text)^,length(memo1.text)); 一句搞掂
 
我都试过了,但是还是没法...........
有朋友有方法吗?
 
发送:nmudp1.SendBuffer(PChar(memo1.text)^,length(memo1.text)+1);
 
上面的没错,但当字符达到5个以上就有乱码了?
为什么????
 
count怎么不赋初值?他是传入、传出的值,传入最大可以接受的字符数
ReadBuffer之前需要先 count:=numberbytes
 
PIPI兄, 这个程序不复杂,书上的,能否给个邮箱,我给你邮来调试调试?
 
ReadBuffer之前需要先 count:=numberbytes.给了一个初值,好像还是有乱码呀?
 
我也试过很多次,出现和你一样的问题......
用stream就没问题,我估计是nmudp的bug,反正也看不了源代码,我是解决不了的.....
其实用winsock做个udp的控件也只用100多行,自己写或者改用indy的吧!
 
呵呵,用ICS和INDY的控件把,NM系列的BUG多多
 
代码如下:
点发送按钮:
procedure TForm1.Button1Click(Sender: TObject);
var txt:array[0..59] of char;//这个长度你可以动态设置
begin
if memo1.Text ='' then
begin
statusbar1.SimpleText :='null to send!';
exit;
end;
StrpCopy(txt,memo1.text);
nmudp1.SendBuffer(txt,60);
end;
接收时:
procedure TForm1.NMUDP1DataReceived(Sender: TComponent;
NumberBytes: Integer; FromIP: String; Port: Integer);
var txt:array[0..59] of char;
count:integer;
begin
statusbar1.SimpleText :='receving data';
nmudp1.ReadBuffer(txt,60);
memo2.Lines.Add('À´×Ô:'+FromIP+'¶Ë¿Ú:'+inttostr(port)+'ÄÚÈÝΪ:'+txt);
statusbar1.SimpleText :='data received';
end;

 
顶部