|
用任意语言编一个TCP的socket,然后Delphi与之通信:- uses IdTCPClient;
- var TCPClient : TIdTCPClient;
- procedure TForm1.sendAndReceive(conn: TIdTCPClient);
- var
- client_text, recvString: string;
- buf: array[0..1023] of Char;
- buffer: TBytes;
- leng_of_msg : Longint;
- bytes_length, bytes_body, raw_client_to_send: TBytes;
- begin
- try
- client_text := '|CONSUMER|INIT|RaspiFreeLancer|RaspiCardBoard|1|';
- memo1.Lines.Add('Will send:' + client_text);
- leng_of_msg := length(client_text);
- memo1.Lines.Add(inttostr(leng_of_msg));
- bytes_length := longToBytes(leng_of_msg);
- bytes_body := stringToBytes(client_text);
- raw_client_to_send := combineTwoBytes(bytes_length, bytes_body); // 都将两个字节组合到一块
- if (conn.Connected) then // and (TCPclient.Socket.Opened) then
- begin
- //TCPClient.IOHandler.(client_text, length(client_text)); // 发送数据到服务器
- conn.IOHandler.WriteDirect(raw_client_to_send);
- end;
-
- if (conn.Connected) and (not conn.Socket.InputBufferIsEmpty) then
- begin
- conn.IOHandler.CheckForDataOnSource(100); // fill the output buffer with a timeout of 100ms.
- conn.IOHandler.InputBuffer.ExtractToBytes(buffer, -1, True, -1); // False???
- memo2.Lines.Add('Has recved value:' + bytesToString(buffer));
- end;
- // recvString := TCPClient.IOHandler.ReadLn; // 从服务器接收数据
- // TCPClient.IOHandler.readln(buf, 1024);
- // setLength(buffer, 100);
- // TCPClient.IOHandler.ReadBytes(buffer,100,False); // ReadBytes(buffer, 1024, True);
- // memo1.Lines.add('Read from server:' + recvString); // 显示服务器响应
- except
- on e: exception do
- memo1.Lines.add('Error:' + e.className + e.message);
- end;
- end;
- function TForm1.combineTwoBytes(const bytes1, bytes2: TBytes): TBytes;
- begin
- setLength(result, length(bytes1) + length(bytes2));
- copyMemory(@result[0], @bytes1[0], length(bytes1));
- copyMemory(@result[length(bytes1)], @bytes2[0], length(bytes2));
- end;
复制代码- procedure TForm1.FormCreate(Sender: TObject);
- begin
- TCPClient := TIdTCPClient.Create(nil);
- try
- TCPClient.Host := '172.17.10.100'; // Python服务器的IP地址
- TCPClient.Port := 65535; // Python服务器监听的端口
- //TCPClient.ConnectTimeout := 5000; // 连接超时时间
- //TCPClient.ReadTimeout := 2000; // 读取超时时间
- TCPClient.Connect; // 连接到服务器
- //TCPClient.socket.open;
- //sendAndReceive(TCPClient);
- except
- on e: Exception do
- begin
- TCPClient.Disconnect; // 断开连接
- TCPClient.Free;
- memo2.Lines.Add('Error conn:' + e.Message);
- end;
- end;
- end;
复制代码
暂时就是这么编的,帧的前部是后部的长度,用一个长整型记录,之后两个部分都转成字节,然后相连接,发送。
收取的也是字节,转成字串输出。数据的转换请看前面一个帖子。
用到TIdTCPClient, Delphi2007 编译通过。
暂时这么编的。似乎有些时候不太稳定,欢迎大家批评。 |
|