1. 程式人生 > >Erlang連線Golang服務1-初探

Erlang連線Golang服務1-初探

Erlang連線Golang服務1-初探

為啥要做這個?好玩唄!
使用Erlang作為客戶端,Golang寫服務端,使用TCP協議連線。

下面的是Golang簡單的服務端的程式碼,一個單執行緒的伺服器,監聽8080埠,收到資訊就列印收到的內容。

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "net"
)

func main() {
    listener, err := net.Listen("tcp", "localhost:8080")
    if err != nil {
        log.Print(err)
    }
    for
{ conn, err := listener.Accept() if err != nil { log.Print(err) // e.g., connection aborted continue } handleConn(conn) // handle one connection at a time } } func handleConn(conn net.Conn) { defer conn.Close() result, err := ioutil.ReadAll(conn) //獲得收到的資料
if err != nil { log.Fatal(err) } for index, tb := range result { fmt.Printf("index=%d, content=%c\n", index, tb) } // fmt.Printf(string(result)) fmt.Println("=============================================") }

下面的是Erlang客戶端的程式碼

%% 檔名mclient.erl
-module(mclient)
. -author("Hua"). %% API -export([client/0]). client() -> SomeHostInNet = "localhost", Port = 8080, %% {packet,4}後面的數字代表資料頭的位元組 {ok, Sock} = gen_tcp:connect(SomeHostInNet, Port, [binary, {packet, 4}]), ok = gen_tcp:send(Sock, "Some Data"), ok = gen_tcp:close(Sock).

當為{packet, 0}

index=0, content=S
index=1, content=o
index=2, content=m
index=3, content=e
index=4, content=
index=5, content=D
index=6, content=a
index=7, content=t
index=8, content=a

當為{packet, 4}

index=0, content=
index=1, content=
index=2, content=
index=3, content=
index=4, content=S
index=5, content=o
index=6, content=m
index=7, content=e
index=8, content=
index=9, content=D
index=10, content=a
index=11, content=t
index=12, content=a