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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值