long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

go-net

Posted at 2021-03-28 golang 网络 

golang TCP/UDP连接

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53

func UdpEcho() {
upd, err := net.ResolveUDPAddr("udp4", ":1400")
conn, err := net.ListenUDP("udp4", upd)
if err != nil {
fmt.Println(err)
return
}
defer conn.Close()
readBuf := make([]byte, 1024)
for {
time.Sleep(50 * time.Millisecond)
n, remoteAddr, err := conn.ReadFromUDP(readBuf)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println("客户端 ip:", remoteAddr.IP, "端口:", remoteAddr.Port, "数据:", string(readBuf[:n]))
peerConn, err := net.DialUDP("udp4", nil, remoteAddr)
if err != nil {
fmt.Println(err)
continue
}
fmt.Println("发送响应....")
peerConn.Write(writeBuf)
peerConn.Close()
}
}

func TCPEcho(){
server, err := net.Listen("tcp", ":1402")
if err != nil {
fmt.Println(err)
return
}

for true {
select {
case <- exit_ch:
break
default:
conn, err := server.Accept()
fmt.Println("客户端连接了")
if err != nil {
fmt.Println(err)
}else{
go func(conn){
// 处理请求数据和响应
}{}
}
}
}
}

Golang HttpRequest

使用golang构建Http请求

1
2
3
4
5
6
7
8
9
10
requestBody := fmt.Sprintf("{\"jsonrpc\":\"2.0\",\"method\":\"aria2.tellStatus\",\"id\":\"QXJpYU5nXzE2MTY4NTg0ODZfMC44NzA1NzgxMzY4ODM5NjUz\", \"params\":[\"%s\"]}",gid)
reader := bytes.NewReader([]byte(requestBody))
request,err := http.NewRequest("POST", rpc_url, reader)
if err != nil {
fmt.Println(err)
return nil, err
}
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)

Https免认证证书

1
2
3
client := http.Client{Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true,}
}}

aira2c简单调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110

var rpc_url = "http://localhost:6800/jsonrpc"

func AddNewDownloadTask(url string, dir string, filename string) (string, error) {
requestBody := fmt.Sprintf("{\"jsonrpc\":\"2.0\",\"id\":\"QXJpYU5nXzE2MTY4NTc3MTZfMC4wNDc5NjM4NzcyODIzNTc2MjU=\",\"method\":\"aria2.addUri\",\"params\":[[\"%s\"],{\"dir\":\"%s\", \"out\":\"%s\",\"allow-overwrite\":\"true\"}]}",
url, dir, filename)

reader := bytes.NewReader([]byte(requestBody))
request,err := http.NewRequest("POST", rpc_url, reader)
if err != nil {
fmt.Println(err)
return "", err
}
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return "",err
}
defer response.Body.Close()
resp, err := ioutil.ReadAll(response.Body)
if err != nil {
return "",err
}
res := struct {
Id string `json:"id"`
Result string `json:"result"`
}{}
err = json.Unmarshal(resp, &res)
if err != nil {
return "",err
}
return res.Result, nil
}

type GetGlobalStatResponseDAO struct {
Id string `json:"id"`
Jsonrpc string `json:"jsonrpc"`
Result struct {
DownloadSpeed string `json:"downloadSpeed"`
NumActive string `json:"numActive"`
NumStopped string `json:"numStopped"`
NumStoppedTotal string `json:"numStoppedTotal"`
NumWaiting string `json:"numWaiting"`
UploadSpeed string `json:"uploadSpeed"`
} `json:"result"`
}

func GetGlobalStat() (*GetGlobalStatResponseDAO, error){
requestBody := "{\"jsonrpc\":\"2.0\",\"method\":\"aria2.getGlobalStat\",\"id\":\"QXJpYU5nXzE2MTY4NTg0ODZfMC44NzA1NzgxMzY4ODM5NjUz\"}"
reader := bytes.NewReader([]byte(requestBody))
request,err := http.NewRequest("POST", rpc_url, reader)
if err != nil {
fmt.Println(err)
return nil, err
}
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil,err
}
defer response.Body.Close()
resp, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil,err
}
res := GetGlobalStatResponseDAO{}
err = json.Unmarshal(resp, &res)
if err != nil {
return nil,err
}
return &res, nil
}

type TellStatusDAO struct {
Id string `json:"id"`
Jsonrpc string `json:"jsonrpc"`
Result struct {
Status string `json:"status"`
} `json:"result"`
}

func TellStatus(gid string) (*TellStatusDAO, error) {
requestBody := fmt.Sprintf("{\"jsonrpc\":\"2.0\",\"method\":\"aria2.tellStatus\",\"id\":\"QXJpYU5nXzE2MTY4NTg0ODZfMC44NzA1NzgxMzY4ODM5NjUz\", \"params\":[\"%s\"]}",gid)
reader := bytes.NewReader([]byte(requestBody))
request,err := http.NewRequest("POST", rpc_url, reader)
if err != nil {
fmt.Println(err)
return nil, err
}
request.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
return nil,err
}
defer response.Body.Close()
resp, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil,err
}
res := TellStatusDAO{}
err = json.Unmarshal(resp, &res)
if err != nil {
return nil,err
}
return &res, nil
}

go-MQTT客户端demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main

import (
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"log"
"os"
"time"
)

func sub(client mqtt.Client, topic string) {
token := client.Subscribe(topic, 1, nil)
token.Wait()
log.Printf("Subscribed to topic %s", topic)
}
func public(client mqtt.Client, topic string) {
for i := 0;i < 10;i ++ {
payload := fmt.Sprintf("Paylod data[%d]", i)
token := client.Publish(topic, 0, false, payload)
token.Wait()
time.Sleep(1 * time.Second)
}
}

func main() {
args := os.Args
if len(args) < 4 {
return
}
clienId := args[1]
subTopic := args[2]
pubTopic := args[3]

var broker = "localhost"
var port = 1883
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
opts.SetClientID(clienId)
opts.SetUsername("emqx")
opts.SetPassword("public")
opts.SetDefaultPublishHandler(func(client mqtt.Client, message mqtt.Message) {
log.Printf("Recieve message : %s from topic: %s\n", message.Payload(), message.Topic())
})
opts.OnConnect = func(client mqtt.Client) {
log.Println("Connected")
}

opts.OnConnectionLost = func(client mqtt.Client, err error) {
log.Printf("Connect lost: %v", err)
}

client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
log.Println("start???")
sub(client, subTopic)
public(client, pubTopic)

client.Disconnect(250)
}

Share 

 Previous post: go-加解密 Next post: OpenSSL生成SSL证书 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo