일부 예제

예제 1

프로토콜 정의

  • 헤더는 전체 데이터 패킷 길이를 저장하기 위해 고정 10바이트 길이로, 비트 수가 부족할 경우 0으로 채움
  • 데이터 형식은 xml임

데이터 패킷 샘플

0000000121<?xml version="1.0" encoding="ISO-8859-1"?>
<request>
    <module>user</module>
    <action>getInfo</action>
</request>

여기서 0000000121은 전체 데이터 패킷의 길이를 나타내며, 뒤에 xml 데이터 형식의 본문 내용이 뒤따릅니다.

프로토콜 구현

namespace Protocols;
class XmlProtocol
{
    public static function input($recv_buffer)
    {
        if(strlen($recv_buffer) < 10)
        {
            // 10바이트 미만, 0을 반환하고 계속 데이터를 기다림
            return 0;
        }
        // 패킷 길이 반환, 패킷 길이는 헤더 데이터 길이 + 본문 길이를 포함
        $total_len = base_convert(substr($recv_buffer, 0, 10), 10, 10);
        return $total_len;
    }

    public static function decode($recv_buffer)
    {
        // 요청 본문
        $body = substr($recv_buffer, 10);
        return simplexml_load_string($body);
    }

    public static function encode($xml_string)
    {
        // 본문 + 헤더의 길이
        $total_length = strlen($xml_string)+10;
        // 길이 부분 10바이트로 채우기, 비트 수 부족시 0으로 채움
        $total_length_str = str_pad($total_length, 10, '0', STR_PAD_LEFT);
        // 데이터 반환
        return $total_length_str . $xml_string;
    }
}

예제 2

프로토콜 정의

  • 헤더는 4바이트 네트워크 바이트 순서의 unsigned int로, 전체 패킷의 길이를 표시
  • 데이터 부분은 Json 문자열임

데이터 패킷 샘플

****{"type":"message","content":"hello all"}

여기서 헤더의 4바이트 * 문자는 네트워크 바이트 순서의 unsigned int 데이터로, 보이지 않는 문자이며, 뒤따르는 것은 Json 형식의 데이터 본문입니다.

프로토콜 구현

namespace Protocols;
class JsonInt
{
    public static function input($recv_buffer)
    {
        // 수신된 데이터가 4바이트 미만이면 패킷의 길이를 알 수 없어 0을 반환하고 계속 데이터 기다림
        if(strlen($recv_buffer)<4)
        {
            return 0;
        }
        // unpack 함수를 사용하여 헤더의 4바이트를 숫자로 변환, 헤더의 4바이트는 전체 데이터 패킷의 길이임
        $unpack_data = unpack('Ntotal_length', $recv_buffer);
        return $unpack_data['total_length'];
    }

    public static function decode($recv_buffer)
    {
        // 헤더 4바이트를 제거하여 본문 Json 데이터를 얻음
        $body_json_str = substr($recv_buffer, 4);
        // json 디코드
        return json_decode($body_json_str, true);
    }

    public static function encode($data)
    {
        // Json 인코딩으로 패킷 본문 생성
        $body_json_str = json_encode($data);
        // 전체 패킷의 길이 계산, 헤더 4바이트 + 본문 바이트 수
        $total_length = 4 + strlen($body_json_str);
        // 패킹된 데이터 반환
        return pack('N',$total_length) . $body_json_str;
    }
}

예제 3 (이진 프로토콜을 사용하여 파일 업로드)

프로토콜 정의

struct
{
  unsigned int total_len;  // 전체 패킷의 길이, 빅 엔디안 네트워크 바이트 순서
  char         name_len;   // 파일 이름의 길이
  char         name[name_len]; // 파일 이름
  char         file[total_len - BinaryTransfer::PACKAGE_HEAD_LEN - name_len]; // 파일 데이터
}

프로토콜 샘플

 *****logo.png****************** 

여기서 헤더의 4바이트 문자는 네트워크 바이트 순서의 unsigned int 데이터로, 보이지 않는 문자이며, 5번째 는 파일 이름 길이를 1바이트로 저장하고, 다음은 파일 이름이며, 그 다음은 원래의 이진 파일 데이터입니다.

프로토콜 구현

namespace Protocols;
class BinaryTransfer
{
    // 프로토콜 헤더 길이
    const PACKAGE_HEAD_LEN = 5;

    public static function input($recv_buffer)
    {
        // 프로토콜 헤더 길이가 충분하지 않으면 계속 기다림
        if(strlen($recv_buffer) < self::PACKAGE_HEAD_LEN)
        {
            return 0;
        }
        // 언팩
        $package_data = unpack('Ntotal_len/Cname_len', $recv_buffer);
        // 패킷 길이 반환
        return $package_data['total_len'];
    }

    public static function decode($recv_buffer)
    {
        // 언팩
        $package_data = unpack('Ntotal_len/Cname_len', $recv_buffer);
        // 파일 이름 길이
        $name_len = $package_data['name_len'];
        // 데이터 스트림에서 파일 이름 추출
        $file_name = substr($recv_buffer, self::PACKAGE_HEAD_LEN, $name_len);
        // 데이터 스트림에서 파일 이진 데이터 추출
        $file_data = substr($recv_buffer, self::PACKAGE_HEAD_LEN + $name_len);
         return array(
             'file_name' => $file_name,
             'file_data' => $file_data,
         );
    }

    public static function encode($data)
    {
        // 클라이언트에 전송할 데이터를 필요한 대로 인코딩할 수 있으며, 여기는 텍스트 그대로 반환
        return $data;
    }
}

서버 측 프로토콜 사용 예제

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('BinaryTransfer://0.0.0.0:8333');
// 파일을 tmp 아래에 저장
$worker->onMessage = function(TcpConnection $connection, $data)
{
    $save_path = '/tmp/'.$data['file_name'];
    file_put_contents($save_path, $data['file_data']);
    $connection->send("upload success. save path $save_path");
};

Worker::runAll();

클라이언트 파일 client.php (여기서 php로 클라이언트를 에뮬레이션하여 업로드)

<?php
/** 파일 업로드 클라이언트 **/
// 업로드 주소
$address = "127.0.0.1:8333";
// 업로드 파일 경로 매개변수를 검사
if(!isset($argv[1]))
{
   exit("use php client.php \$file_path\n");
}
// 업로드할 파일 경로
$file_to_transfer = trim($argv[1]);
// 업로드할 파일이 로컬에 존재하지 않음
if(!is_file($file_to_transfer))
{
    exit("$file_to_transfer not exist\n");
}
// 소켓 연결 설정
$client = stream_socket_client($address, $errno, $errmsg);
if(!$client)
{
    exit("$errmsg\n");
}
// 차단 모드로 설정
stream_set_blocking($client, 1);
// 파일 이름
$file_name = basename($file_to_transfer);
// 파일 이름 길이
$name_len = strlen($file_name);
// 파일 이진 데이터
$file_data = file_get_contents($file_to_transfer);
// 프로토콜 헤더 길이 4바이트 패킷 길이 + 1바이트 파일 이름 길이
$PACKAGE_HEAD_LEN = 5;
// 프로토콜 패킷
$package = pack('NC', $PACKAGE_HEAD_LEN  + strlen($file_name) + strlen($file_data), $name_len) . $file_name . $file_data;
// 업로드 실행
fwrite($client, $package);
// 결과 출력
echo fread($client, 8192),"\n";

클라이언트 사용 예제

명령줄에서 php client.php <파일 경로> 실행

예를 들어 php client.php abc.jpg

예제 4 (텍스트 프로토콜을 사용하여 파일 업로드)

프로토콜 정의

json + 줄 바꿈, json에는 파일 이름과 base64_encode 인코딩된 (크기를 1/3 증가시킴) 파일 데이터가 포함됨

프로토콜 샘플

{"file_name":"logo.png","file_data":"PD9waHAKLyo......"}\n

주의: 끝 부분에 줄 바꿈 문자가 있으며, PHP에서 더블 인용 문자 "\n"로 표시됨

프로토콜 구현

namespace Protocols;
class TextTransfer
{
    public static function input($recv_buffer)
    {
        $recv_len = strlen($recv_buffer);
        if($recv_buffer[$recv_len-1] !== "\n")
        {
            return 0;
        }
        return strlen($recv_buffer);
    }

    public static function decode($recv_buffer)
    {
        // 언팩
        $package_data = json_decode(trim($recv_buffer), true);
        // 파일 이름 추출
        $file_name = $package_data['file_name'];
        // base64_encode된 파일 데이터 추출
        $file_data = $package_data['file_data'];
        // base64_decode하여 원래의 이진 파일 데이터로 복원
        $file_data = base64_decode($file_data);
        // 데이터 반환
        return array(
             'file_name' => $file_name,
             'file_data' => $file_data,
         );
    }

    public static function encode($data)
    {
        // 클라이언트에게 전송할 데이터를 필요에 따라 인코딩할 수 있으며, 여기는 텍스트 그대로 반환
        return $data;
    }
}

서버 측 프로토콜 사용 예제

설명: 이진 업로드와 거의 동일한 비즈니스 코드를 변경하지 않고 프로토콜을 전환할 수 있음

use Workerman\Worker;
use Workerman\Connection\TcpConnection;
require_once __DIR__ . '/vendor/autoload.php';

$worker = new Worker('TextTransfer://0.0.0.0:8333');
// 파일을 tmp 아래에 저장
$worker->onMessage = function(TcpConnection $connection, $data)
{
    $save_path = '/tmp/'.$data['file_name'];
    file_put_contents($save_path, $data['file_data']);
    $connection->send("upload success. save path $save_path");
};

Worker::runAll();

클라이언트 파일 textclient.php (여기서 php로 클라이언트를 에뮬레이션하여 업로드)

<?php
/** 파일 업로드 클라이언트 **/
// 업로드 주소
$address = "127.0.0.1:8333";
// 업로드 파일 경로 매개변수를 검사
if(!isset($argv[1]))
{
   exit("use php client.php \$file_path\n");
}
// 업로드 파일 경로
$file_to_transfer = trim($argv[1]);
// 업로드할 파일이 로컬에 존재하지 않음
if(!is_file($file_to_transfer))
{
    exit("$file_to_transfer not exist\n");
}
// 소켓 연결 설정
$client = stream_socket_client($address, $errno, $errmsg);
if(!$client)
{
    exit("$errmsg\n");
}
stream_set_blocking($client, 1);
// 파일 이름
$file_name = basename($file_to_transfer);
// 파일 이진 데이터
$file_data = file_get_contents($file_to_transfer);
// base64 인코딩
$file_data = base64_encode($file_data);
// 데이터 패킷
$package_data = array(
    'file_name' => $file_name,
    'file_data' => $file_data,
);
// 프로토콜 패킷 json + 줄 바꿈
$package = json_encode($package_data)."\n";
// 업로드 실행
fwrite($client, $package);
// 결과 출력
echo fread($client, 8192),"\n";

클라이언트 사용 예제

명령줄에서 php textclient.php <파일 경로> 실행

예를 들어 php textclient.php abc.jpg