Golang TCP客户端退出

huangapple go评论80阅读模式
英文:

Golang TCP client exits

问题

我正在尝试用Golang编写一个简单的客户端,但是一运行它就退出了。

package main

import (
	"fmt"
	"net"
	"os"
	"bufio"
	"sync"
)

func main() {

	conn, err := net.Dial("tcp", "localhost:8081")
	if err != nil {
		fmt.Println(err)
		conn.Close()
	}
	fmt.Println("Got connection, type anything...new line sends and quit quits the session")
	go sendRequest(conn)
}


func sendRequest(conn net.Conn) {

	reader := bufio.NewReader(os.Stdin)
	var wg sync.WaitGroup
	for {
		buff := make([]byte, 2048)
		line, err := reader.ReadString('\n')
		wg.Add(1)
		if err != nil {
			fmt.Println("Error while reading string from stdin",err)
			conn.Close()
			break
		}

		copy(buff[:], line)
		nr, err := conn.Write(buff)
		if err != nil {
			fmt.Println("Error while writing from client to connection", err)
			break
		}
		fmt.Println(" Wrote : ", nr)
		wg.Done()
		buff = buff[:0]
	}
	wg.Wait()

}

当我尝试运行它时,输出如下:

Got connection, type anything...new line sends and quit quits the session

Process finished with exit code 0

我期望这段代码会打开标准输入(终端)并等待输入文本,但它立即退出。我应该用其他代码替换它以从标准输入读取吗?

英文:

I am trying to write a simple client in Golang but it exits as soon as I run it,

package main

    import (
    	"fmt"
    	"net"
    	"os"
    	"bufio"
    	"sync"
    )
    
    func main() {
    
    	conn, err := net.Dial("tcp", "localhost:8081")
    	if err != nil {
    		fmt.Println(err);
    		conn.Close();
    	}
    	fmt.Println("Got connection, type anything...new line sends and quit quits the session");
    	go sendRequest(conn)
    }
    
    
    func sendRequest(conn net.Conn) {
    
    	reader := bufio.NewReader(os.Stdin)
    	var wg sync.WaitGroup
    	for {
    		buff := make([]byte, 2048);
    		line, err := reader.ReadString('\n')
    		wg.Add(1);
    		if err != nil {
    			fmt.Println("Error while reading string from stdin",err)
    			conn.Close()
    			break;
    		}
    
    		copy(buff[:], line)
    		nr, err := conn.Write(buff)
    		if err != nil {
    			fmt.Println("Error while writing from client to connection", err);
    			break;
    		}
    		fmt.Println(" Wrote : ", nr);
    		wg.Done()
    		buff = buff[:0]
    	}
    	wg.Wait()
    
    }

And when trying to run it, I get the following as output

Got connection, type anything...new line sends and quit quits the session

Process finished with exit code 0

I am expecting that the code would make stdin(terminal) open and wait for input text but it exits immediately. Should I be replacing the code with something else for reading from stdin

答案1

得分: 2

一个Go程序在main函数返回时退出。

简单的修复方法是直接调用sendRequest函数。在这个程序中不需要使用goroutine。

func main() {
  conn, err := net.Dial("tcp", "localhost:8081")
  if err != nil {
    fmt.Println(err)
    conn.Close()
  }
  fmt.Println("Got connection, type anything...new line sends and quit quits the session")
  sendRequest(conn) // <-- 这一行去掉了go关键字
}

如果需要使用goroutine,可以使用sync.WaitGroup使main函数等待goroutine完成:

func main() {
  conn, err := net.Dial("tcp", "localhost:8081")
  if err != nil {
    fmt.Println(err)
    conn.Close()
  }
  var wg sync.WaitGroup
  fmt.Println("Got connection, type anything...new line sends and quit quits the session")
  wg.Add(1)
  go sendRequest(&wg, conn)
  wg.Wait()
}

func sendRequest(wg *sync.WaitGroup, conn net.Conn) {
  defer wg.Done()
  // 之前的代码
}
英文:

A Go program exits when the main function returns.

The simple fix is to call sendRequest directly. The goroutine is not needed in this program.

func main() {

  conn, err := net.Dial(&quot;tcp&quot;, &quot;localhost:8081&quot;)
  if err != nil {
    fmt.Println(err);
    conn.Close();
  }
  fmt.Println(&quot;Got connection, type anything...new line sends and quit quits the session&quot;);
  sendRequest(conn) // &lt;-- go removed from this line.
}

If the goroutine is required, then use a sync.WaitGroup to make main wait for goroutines to complete:

func main() {
  conn, err := net.Dial(&quot;tcp&quot;, &quot;localhost:8081&quot;)
  if err != nil {
    fmt.Println(err);
    conn.Close();
  }
  var wg sync.WaitGroup
  fmt.Println(&quot;Got connection, type anything...new line sends and quit quits the session&quot;);
  wg.Add(1)
  go sendRequest(&amp;wg, conn)
  wg.Wait()
}

func sendRequest(wg *sync.WaitGroup, conn net.Conn) {
  defer wg.Done()
  // same code as before
}

huangapple
  • 本文由 发表于 2014年10月11日 19:43:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/26314257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定