GolangNote

Golang笔记

用Go 写一个简单的TCP 服务

Permalink

Go 很适于网络编程,下面是实现一个简单的 TCP 服务

用Go 写一个简单的TCP 服务

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

import (
  "bytes"
  "fmt"
  "net"
  "os"
  "strconv"
)

const (
  CONN_HOST = ""
  CONN_PORT = "3333"
  CONN_TYPE = "tcp"
)

func main() {
  // Listen for incoming connections.
  l, err := net.Listen(CONN_TYPE, ":"+CONN_PORT)
  if err != nil {
    fmt.Println("Error listening:", err.Error())
    os.Exit(1)
  }
  // Close the listener when the application closes.
  defer l.Close()
  fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
  for {
    // Listen for an incoming connection.
    conn, err := l.Accept()
    if err != nil {
      fmt.Println("Error accepting: ", err.Error())
      os.Exit(1)
    }

    //logs an incoming message
    fmt.Printf("Received message %s -> %s \n", conn.RemoteAddr(), conn.LocalAddr())

    // Handle connections in a new goroutine.
    go handleRequest(conn)
  }
}

// Handles incoming requests.
func handleRequest(conn net.Conn) {
  // Make a buffer to hold incoming data.
  buf := make([]byte, 1024)
  // Read the incoming connection into the buffer.
  reqLen, err := conn.Read(buf)
  if err != nil {
    fmt.Println("Error reading:", err.Error())
  }
  // Builds the message.
  message := "Hi, I received your message! It was "
  message += strconv.Itoa(reqLen)
  message += " bytes long and that's what it said: \""
  n := bytes.Index(buf, []byte{0})
  message += string(buf[:n-1])
  message += "\" ! Honestly I have no clue about what to do with your messages, so Bye Bye!\n"

  // Write the message in the connection channel.
  conn.Write([]byte(message))
  // Close the connection when you're done with it.
  conn.Close()
}

在终端运行:

Bash: echo
1
echo -n "test out the server" | nc localhost 3333

就会看到

plaintext:
1
2
Hi, I received your message! It was 19 bytes long and that's what it said: "test out the serve" ! 
Honestly I have no clue about what to do with your messages, so Bye Bye!

原文 Creating a simple TCP server in Go

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

Related articles

Golang实现简单的Socks5代理

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

Golang http IPv4/IPv6 服务

Golang 的网络服务,如果不指定IPv4 或 IPv6,如果VPS 同时支持 IPv4 和 IPv6,`net.Listen()` 只会监听 IPv6 地址。但这不影响客户端使用 IPv4 地址来访问。...

vuego: 用GO编写 vue.js 前端

vuego一个基于WASM 对Vue.js 的封装,使用Web Assembly 编译。可以让开发者用go 来写Vue.js 前端脚本。...

Write a Comment to "用Go 写一个简单的TCP 服务"

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