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

Go 1.5.1 更新的功能

Go 1.5.1版本对编译器,汇编器, fmt, net/textproto, net/http, 和 runtime 包的 bug 修复。...

Golang http IPv4/IPv6 服务

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

centrifuge: 实时消息服务

构建实时消息服务的方案有很多种,centrifuge是用go 实现的一种,功能确实不错,基于Websocket SockJS 通信。...

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

Submit Comment Login
Based on Golang + fastHTTP + sdb | go1.20 Processed in 1ms