Pure zmq4 based on golang 오픈소스를 활용하여 PUB/SUB을 테스트

  • Publish golang 소스코드 작성
  • Subscription golang 소스코드 작성
  • 테스트

ZeroMq 오픈소스 URL

 

go-zeromq/zmq4

[WIP] Pure-Go implementation of ZeroMQ-4. Contribute to go-zeromq/zmq4 development by creating an account on GitHub.

github.com

download go command

  • go get github.com/go-zeromq/zmq4
package main
import (
        "context"
        "log"
        "time"
        "github.com/go-zeromq/zmq4"
)

func main() {
        log.SetPrefix("psenvpub: ")
        // prepare the publisher
        pub := zmq4.NewPub(context.Background())
        defer pub.Close()

        err := pub.Listen("tcp://*:5563")
        if err != nil {
                log.Fatalf("could not listen: %v", err)
        }

        msgA := zmq4.NewMsgFrom(
                []byte("test1"), //This message has named "test1" key
                []byte("My key is test1"),
        )
        msgB := zmq4.NewMsgFrom(
                []byte("test2"), //This message has named "test2" key
                []byte("my key is test2"),
        )
        for {
                err = pub.Send(msgA)
                if err != nil {
                        log.Fatal(err)
                }
                err = pub.Send(msgB)
                if err != nil {
                        log.Fatal(err)
                }
                time.Sleep(time.Second)
        }
}

publish 테스트코드

package main
import (
        "context"
        "log"
        "github.com/go-zeromq/zmq4"
)

func main() {
        log.SetPrefix("psenvsub: ")
        //  Prepare our subscriber
        sub := zmq4.NewSub(context.Background())
        defer sub.Close()
        err := sub.Dial("tcp://localhost:5563")
        if err != nil {
                log.Fatalf("could not dial: %v", err)
        }
        err = sub.SetOption(zmq4.OptionSubscribe, "test1") //Received only named "test1" key.
        if err != nil {
                log.Fatalf("could not subscribe: %v", err)
        }
        for {
                // Read envelope
                msg, err := sub.Recv()
                if err != nil {
                        log.Fatalf("could not receive message: %v", err)
                }
                log.Printf("[%s] %s\n", msg.Frames[0], msg.Frames[1])
        }
}

Subscription 테스트코드

 

테스트코드의 메시지 송수신 확인

'언어 > Golang' 카테고리의 다른 글

Go 오픈소스를 이용하여 C코드에서 활용 할 수 있는 Library 테스트  (0) 2020.11.23
Golang  (0) 2017.05.22

ZeroMQ Go 오픈소스를 활용하여 C코드에서 사용 할 수 있는 Library 테스트

 

(ZeroMQ callback function)

  • Make a library for using at C code.
  • Make a C code.
  • Build by linking a library to C code.

ZeroMq Opensource URL

 

go-zeromq/zmq4

[WIP] Pure-Go implementation of ZeroMQ-4. Contribute to go-zeromq/zmq4 development by creating an account on GitHub.

github.com

download go command

  • go get github.com/go-zeromq/zmq4
package main
/*
#include <stdio.h>
typedef int (*FuncPtr)(int, int);

static inline int Shoot(FuncPtr func,int a,int b)
{
        func(a,b);
}
*/
import "C"
import (
        "context"
        "github.com/go-zeromq/zmq4"
        "log"
)

//export Rcv
func Rcv(t C.FuncPtr) {   
        log.SetPrefix("psenvsub: ")
        sub := zmq4.NewSub(context.Background())
        defer sub.Close()
        err := sub.Dial("tcp://localhost:5563")
        if err != nil {
                log.Fatalf("could not dial: %v", err)
        }
        err = sub.SetOption(zmq4.OptionSubscribe, "test1") //Received only named "test1" key.
        if err != nil {
                log.Fatalf("could not subscribe: %v", err)
        }
        var a int =0
        var b int =0
        for {
                msg, err := sub.Recv()
                if err != nil {
                        log.Fatalf("could not receive message: %v", err)
                }
                log.Printf("[%s] %s\n", msg.Frames[0], msg.Frames[1])
                C.Shoot(t,C.int(a),C.int(b))

                a+=1
                b+=1
        }
}

func main() {} // 반드시 main function 작성.

library.go(수신용 라이브러리 Go파일)

go tool 명령어를 실행하여 라이브러리 빌드

  • command 실행-> go build -o library.so -buildmode=c-shared library.go
#include <stdio.h>
#include "library.h"

int plus (int first, int second)
{
    printf("first:%d second:%d!!!!!!!!!!!!!!!!!!!!!!!!!!!\n",first,second);
        return first + second;
}

int main()
{
        Rcv(plus);
        return 0;
}

rev.c(라이브러리 callback함수)

gcc를 이용하여 빌드

  • gcc -o rcv ./rcv.c ./library.so

 

 

'언어 > Golang' 카테고리의 다른 글

Pure zmq4 based on golang 오픈소스를 활용하여 PUB/SUB 테스트  (0) 2020.11.23
Golang  (0) 2017.05.22

golang의 기본적인 특징

 

 기본특징

  1. Compile 언어
  2. 시스템 프로그래밍 언어
  3. ARM , X86 완벽 지원
  4. windows, linux, mac 지원
  5. Class 미지원
  6. 상속 및 오버로딩 미지원
  7. GC(Garbage Collector)지원
  8. 포인터는 지원하지만 포인터 연산을 지원하지 않음
  9. 엄격한 타입 변환->타입변환을 명시적으로 하지 않으면 컴파일 에러
  10. 객체지향 언어이기도 하고 객체지향 언어가 아니기도 하다.(인터페이스개념을 지원하므로)->상속을 다른 접근 방식으로 지원

 

 C언어의의 비교

  1. 변수 선언
  2. 세미콜론
  3. { }의 올바른 위치 및 의무적 사용 강제화
  4. while문(Go언어는 while문은 없음->for문으로 사용하도록함)
  5. public, private키워드를 지원(함수나 변수의 첫글자가 대문자인 경우 외부에서 접근가능, 소문자인 경우 접근 불가)
  6. switch->Go언어에서는 switch~case문에서 break가 없음.
  7. Go언어의 function은 2개이상의 값을 return할 수 있다.(경험상 활용도가 높고 유용하다.)
  8. 두 변수의 swap는 간결하다.
    1. ex) i, j = j, i
  9. Go언어에서는 변수 선언후 사용하지 않는 변수가 있을 경우 컴파일 오류 발생
  10. Go 언어에서는 암시적 형변환은 없다.(버그 사전방지효과.)

 

 Go 언어로 개발된 대표적인 상용제품

  1. Docker, Kubernetes
  2. Twitch 서비스(게임 중계 사이트) - 아마존이 1억달러에 인수
    • 채팅 기능을 Go 언어로 개발하여 성공(성능이나 안정성이 향상)
  3. Cisco InterCloud 서비스
    1. Private/Public cloud 연결을 통해 IOT 애플리케이션 런칭을 목표로 하는 서비스
  4. Parse.com
    1. Ruby에서 Golang으로 옮김(성능 확장 개선)
  5. 온라인 결제 페이팔(Paypal)
    1. BLE(Bluetooth Low Energy)관련고크
  6. XOR Exchange, Yext, DataDog, CoreOs, New Relic, SoundCloud, MongoDB, Canonical 등.

+ Recent posts