delphi(客户端) socket 与 PHP_socket(服务器) 通信的例子


unit Unit_client;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  ScktComp, StdCtrls, ComCtrls, ExtCtrls;

type
  TForm1 = class(TForm)
    S1: TStatusBar;
    M1: TMemo;
    Client: TClientSocket;
    Edit1: TEdit;
    Button1: TButton;
    Bevel1: TBevel;
    Label1: TLabel;
    edtHost: TEdit;
    Label2: TLabel;
    edtPort: TEdit;
    btnConnect: TButton;
    bntDisConnect: TButton;
    Button2: TButton;
    procedure ClientConnect(Sender: TObject;
      Socket: TCustomWinSocket);
    procedure ClientRead(Sender: TObject; Socket: TCustomWinSocket);
    procedure ClientDisconnect(Sender: TObject; Socket: TCustomWinSocket);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure M1Click(Sender: TObject);
    procedure Button1Click(Sender: TObject);
    procedure btnConnectClick(Sender: TObject);
    procedure Edit1KeyPress(Sender: TObject; var Key: Char);
    procedure FormCreate(Sender: TObject);
    procedure bntDisConnectClick(Sender: TObject);
    procedure Button2Click(Sender: TObject);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;
  TotalLen:Integer;

implementation
uses  ShellAPI;
{$R *.DFM}

//delphi(客户端) socket 与 PHP_socket(服务器) 通信的例子

procedure TForm1.ClientConnect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
S1.Panels.Items[0].Text:='Connect Received';
S1.Panels.items[1].text:='';
end;

procedure TForm1.ClientRead(Sender: TObject; Socket: TCustomWinSocket);
var
  re:pchar;
  sbuf:string;
  relong:integer;
begin
    re:=nil;
    while socket.ReceiveLength>0 do
      begin
        //申请内存
        re:=AllocMem(socket.receivelength);
      TRY
        relong:=socket.ReceiveLength;
        Socket.ReceiveBuf(re^,Socket.receivelength);
        sBuf:=strpas(re);
        Setlength(sbuf,relong);

        //count lenght
        TotalLen:=TotalLen+ relong;
        S1.Panels.Items[1].Text:='Total Received (Byte): ' + IntToStr(TotalLen);
        S1.Update();
      FINALLY
        freemem(re);
      END;
    M1.Lines.Add(sBuf);
  end;
end;

procedure TForm1.ClientDisconnect(Sender: TObject;
  Socket: TCustomWinSocket);
begin
  S1.Panels.Items[0].Text:='Close Connect With Host';
  S1.Panels.Items[0].Text:='';
  M1.Lines.Clear;
  edit1.Text:='';
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  if Client.Active then
    Client.Close;
end;

procedure TForm1.M1Click(Sender: TObject);
begin
Edit1.SetFocus;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
    ShellExecute(self.handle,nil,Pchar(Application.EXEname),nil,nil,SW_Normal);
end;

procedure TForm1.btnConnectClick(Sender: TObject);
begin
    Client.Address:=edtHost.Text;
    Client.Port:=strtoint(edtPort.Text);
    Client.Active:=true;
end;

procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char);
begin
if key=#13 then
  begin
    if not Client.Active then
        btnConnectClick(Sender);
    Client.Socket.SendText(Edit1.Text);
    edit1.SelectAll;
    key:=#0;
  end;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
    edtHost.Text:='192.168.1.101';
    edtPort.Text:='9050';
    TotalLen:=0;
end;

procedure TForm1.bntDisConnectClick(Sender: TObject);
begin
    Client.Active:=False;
end;

procedure TForm1.Button2Click(Sender: TObject);
var
  re:pchar;
  sbuf:string;
  relong:integer;
begin
    re:=nil;
    with Client do begin
    while socket.ReceiveLength>0 do
      begin
        //申请内存
        re:=AllocMem(socket.receivelength);
      TRY
        relong:=socket.ReceiveLength;
        Socket.ReceiveBuf(re^,Socket.receivelength);
        sBuf:=strpas(re);
        Setlength(sbuf,relong);

        //count lenght
        TotalLen:=TotalLen+ relong;
        S1.Panels.Items[1].Text:='Total Received (Byte): ' + IntToStr(TotalLen);
        S1.Update();
      FINALLY
        freemem(re);
      END;
    M1.Lines.Add(sBuf);
  end;
  end;
end;



end.


//php 部分,执行命令:php   server.php

//文件名:server.php

<?php
//确保在连接客户端时不会超时
set_time_limit(0);
    $port = 10081 ;
    $ip = '192.168.1.102';
   
    // create a streaming socket, of type TCP/IP
    $sock = socket_create ( AF_INET , SOCK_STREAM , SOL_TCP );
   
    // set the option to reuse the port
    socket_set_option ( $sock , SOL_SOCKET , SO_REUSEADDR , 1 );
   
    // "bind" the socket to the address to "localhost", on port $port
    // so this means that all connections on this port are now our resposibility to send/recv data, disconnect, etc..
    socket_bind ( $sock , $ip , $port );
   
    // start listen for connections
    socket_listen ( $sock );

    // create a list of all the clients that will be connected to us..
    // add the listening socket to this list
    $clients = array( $sock );
   
    while ( true ) {
        // create a copy, so $clients doesn't get modified by socket_select()
        $read = $clients ;
       
        // get a list of all the clients that have data to be read from
        // if there are no clients with data, go to next iteration
        if ( socket_select ( $read , $write = NULL , $except = NULL , 0 ) < 1 )
            continue;
       
        // check if there is a client trying to connect
        if ( in_array ( $sock , $read )) {
            // accept the client, and add him to the $clients array
            $clients [] = $newsock = socket_accept ( $sock );
           
            // send the client a welcome message
            socket_write ( $newsock , "这是一个delphi(客户端) socket 与 PHP_socket(服务器) 通信的例子 测试,交流QQ:410578660。 but ill make an exception :)\n" .
            "There are " .( count ( $clients ) - 1 ). " client(s) connected to the server\n" );
           
            socket_getpeername ( $newsock , $ip );
            echo "New client connected: { $ip } \n" ;
           
            // remove the listening socket from the clients-with-data array
            $key = array_search ( $sock , $read );
            unset( $read [ $key ]);
        }
       
        // loop through all the clients that have data to read from
        foreach ( $read as $read_sock ) {
            // read until newline or 1024 bytes
            // socket_read while show errors when the client is disconnected, so silence the error messages
            $data = @ socket_read ( $read_sock , 1024 , PHP_NORMAL_READ );
           
            // check if the client is disconnected
            if ( $data === false ) {
                // remove client for $clients array
                $key = array_search ( $read_sock , $clients );
                unset( $clients [ $key ]);
                echo "client disconnected.\n" ;
                // continue to the next client to read from, if any
                continue;
            }
           
            // trim off the trailing/beginning white spaces
            $data = trim ( $data );
           
            // check if there is any data after trimming off the spaces
            if (!empty( $data )) {
           
                // send this to all the clients in the $clients array (except the first one, which is a listening socket)
                foreach ( $clients as $send_sock ) {
               
                    // if its the listening sock or the client that we got the message from, go to the next one in the list
                    if ( $send_sock == $sock || $send_sock == $read_sock )
                        continue;
                   
                    // write the message to the client -- add a newline character to the end of the message
                   socket_write ( $send_sock , $data . "\n" );

                   
                } // end of broadcast foreach
               
            }
           
        } // end of reading foreach
    }

    // close the listening socket
    socket_close ( $sock );
?>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值