2013-08-02 42 views
0

我正在爲客戶端和服務器使用tidudpserver。下面是給出的服務器和客戶端代碼。Delphi xe-3 indy 10無法讀取數據tidudpserver onudpread

unit udp_server; 



procedure TForm4.serverUDPRead(AThread: TIdUDPListenerThread; 
    AData: array of Byte; ABinding: TIdSocketHandle); 
var 
    buffer:tbytes; 
    buffer2:tbytes; 
    i:integer; 
    ex_port:word; 
    i_ip,ex_ip:string; 
    t: string; 
begin 
    ex_ip:=abinding.PeerIP;  //public_ip 
    ex_port:=abinding.PeerPort; //public_port 

    //byte to string 
    setlength(i_ip,length(adata) div 2); 

    // extract private ip from array of byte 
    move(Adata[0],i_ip[1],length(adata)); 

    // client profile {object of tclient } 
    user:=tclient.create(ex_ip,ex_port,i_ip,0,''); 
    //copying public and private endpoints to tclient object 


    setlength(buffer,sizeof(user));   
    move(user,buffer[0],sizeof(user)); // copying object to byte array 


    server.Sendbuffer(abinding.PeerIP,abinding.PeerPort,buffer); 
    // send client info to all connected clients(is this correct way of sending buffer(byte array)?) 
end; 

這是客戶端代碼中給出。我是無法讀取由服務器onudpread程序發送的數據。我怎樣才能將字節數組(包含字符串和單詞類型)轉換爲可讀文本?

unit udp_client; 



procedure TForm4.server2UDPRead(AThread: TIdUDPListenerThread; 
    AData: array of Byte; ABinding: TIdSocketHandle); 
var 
    dest:string; 
    user2:tclient;// i had a tclient class in a separate file 
    buffer:tbytes; 
begin 


    setlength(dest,length(adata)); 
    move(Adata[0],dest[1],length(adata)); // problem is over here ,is this correct? 
end; 

從客戶端發送私有IP

   ip:=getipaddress; //call private ip function taken from (http://delphi.about.com/od/networking/l/aa103100a.htm) 

       setlength(i_ip,length(ip)*2); 

       move(ip[1],i_ip[0],length(i_ip)); 

       server2.Sendbuffer('host',port,i_ip); 

我想要做的UDP打孔針對客戶需要將其信息(公共/私有IP /端口)發送到服務器,然後服務器將交換客戶端信息,然後他們應該能聊天。我很困惑,因爲阿達塔陣列正在接收所有的數據將IP和文本消息相互混合?目前我正在接收垃圾值,它像中文。:-/

+3

請編輯您的問題以刪除所有用戶界面代碼(與您的問題無關)。要弄清楚你所問的所有額外的代碼與你的問題無關。謝謝。 –

回答

3

這段代碼有幾個問題。

在服務器代碼中,將接收到的數據複製到String時,將錯誤的Size值傳遞到Move()。撥打電話SetLength()時要考慮SizeOf(Char)=2,但撥打Move()時不能撥打SizeOf(Char)=2。考慮到Sizeof(Char)只適用於接收到的數據是以UTF-16開頭的(你沒有顯示接收到的數據實際上是什麼樣的)。

更大的問題是,您嘗試向客戶端發送對象,並且這將永遠不會工作。您必須將對象的各個數據成員序列化爲可傳輸的平坦格式,然後發送該數據。例如,IdGlobal單元有許多可用於數據處理的功能<→字節轉換(ToBytes()過載,BytesTo...()過載,CopyTId...()過載等)。因此,您可以分配一個足夠大的單個TIdBytes以容納所有對象的數據,填充數據,然後發送它。收到後,再將其分成單獨的值。你究竟如何做這些取決於你首先要發送什麼樣的數據(你也沒有說明)。

如果你想要更具體的例子,你需要解釋你實際試圖來回交換什麼樣的數據。

0

嘗試使用StringOf函數。它適用於TBytes類型。