GolangNote

Golang笔记

golang 实现简单的socket 服务端/客户端

Permalink

golang 实现简单的 socket 服务端/客户端

server.go

Go: socket 服务端
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
package main

import "net"
import "fmt"
import "bufio"
import "strings" // only needed below for sample processing

func main() {

  fmt.Println("Launching server...")

  // listen on all interfaces
  ln, _ := net.Listen("tcp", ":8081")

  // accept connection on port
  conn, _ := ln.Accept()

  // run loop forever (or until ctrl-c)
  for {
    // will listen for message to process ending in newline (\n)
    message, _ := bufio.NewReader(conn).ReadString('\n')
    // output message received
    fmt.Print("Message Received:", string(message))
    // sample process for string received
    newmessage := strings.ToUpper(message)
    // send new string back to client
    conn.Write([]byte(newmessage + "\n"))
  }
}

client.go

Go: socket 客户端
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package main

import "net"
import "fmt"
import "bufio"
import "os"

func main() {

  // connect to this socket
  conn, _ := net.Dial("tcp", "127.0.0.1:8081")
  for { 
    // read in input from stdin
    reader := bufio.NewReader(os.Stdin)
    fmt.Print("Text to send: ")
    text, _ := reader.ReadString('\n')
    // send to socket
    fmt.Fprintf(conn, text + "\n")
    // listen for reply
    message, _ := bufio.NewReader(conn).ReadString('\n')
    fmt.Print("Message from server: "+message)
  }
}

本文网址: https://golangnote.com/topic/140.html 转摘请注明来源

Related articles

Golang实现简单的Socks5代理

Socks5 代理较 `http/https` 代理有较好的性能,下面是借鉴某个著名开源软件的 local 实现的简单代理。...

Golang 时区时差处理方式

个人习惯用 0 时区时间戳记录时间,可以方便转到不同时区,下面介绍 Golang 时区时差处理...

谷歌翻译的 golang 库推荐

Google 的翻译越来越好了,官方的Golang SDK 已经很完美,这里介绍的是几个非官方发布的有特色的库。...

Write a Comment to "golang 实现简单的socket 服务端/客户端"

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.22.3 Processed in 17ms