Alb*_*lbi 8 tcp tcplistener tcpclient go
我既有TCP服务器又有一个客户端,简单TCP服务器将仅接收传入的数据并进行打印,并且客户端将不断创建套接字连接并将数据循环发送到TCP服务器。
我得到的信息是,如果正确关闭了TCP连接,则此过程应继续进行而不会发生任何崩溃。
但是从客户端到服务器接收到一定数量的数据后,客户端崩溃并报错
total times data send: 16373
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x10d7594]
goroutine 1 [running]:
main.sendData()
/Users/apple/Desktop/Personal/umbrellaserver/src/tests/clinet.go:178
+0xb4
main.main()
/Users/apple/Desktop/Personal/umbrellaserver/src/tests/clinet.go:170
+0x2a
exit status 2
Run Code Online (Sandbox Code Playgroud)
Server.go
package main
import (
"bufio"
"fmt"
"net"
"sync"
)
var wg sync.WaitGroup
var count = 0
var timeX string = ""
var connQueue = make(chan string)
func main() {
tcpListner := startTCPConnection()
incomingTCPListener(tcpListner)
}
//startTCPConnection
func startTCPConnection() net.Listener {
tcpListner, tcpConnectonError := net.Listen("tcp", "localhost:3000")
if tcpConnectonError != nil {
print(tcpConnectonError)
return
}
return tcpListner
}
//incomingTCPListener
func incomingTCPListener(tcpListner net.Listener) {
for {
incomingConnection, incomingConnectionError := tcpListner.Accept()
if incomingConnectionError != nil {
print(incomingConnectionError)
return
}
wg.Add(1)
go processIncomingRequest(incomingConnection)
wg.Wait()
}
}
//processIncomingRequest
func processIncomingRequest(connection net.Conn) {
defer connection.Close()
var scanner = bufio.NewScanner(connection)
var blob = ""
for scanner.Scan() {
fmt.Println("sadd")
text := scanner.Text()
blob += text
}
print(blob)
count++
fmt.Println("totalCount", count)
wg.Done()
}
Run Code Online (Sandbox Code Playgroud)
Client.go
package main
import (
"fmt"
"net"
)
var count = 0
func testJSON2() string {
return `Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.`
}
func main() {
for i := 0; i < 1000000; i++ {
sendData()
}
}
func sendData() {
connection, connectionError := net.Dial("tcp", "localhost:3000")
defer connection.Close()
if connectionError != nil {
fmt.Println(connectionError)
return
}
newmessage := testJSON2()
connection.Write([]byte(newmessage + "\n"))
count++
fmt.Println(count)
}
Run Code Online (Sandbox Code Playgroud)
有什么办法可以避免这种崩溃并使它连续运行? 我完全不熟悉Go,因此,如果我犯了任何愚蠢的错误,对不起。
首先,我建议您是否要打印到stderr,(即您的打印调用)使用fmt库
fmt.Fprintln(os.Stderr, "hello world")
Run Code Online (Sandbox Code Playgroud)
原因:因为不能保证打印功能保持语言不变。1个
其次,通常的做法是给错误命名,就像err您不必拼写错误一样tcpConnectionError。
第三,由于您在connection, connectionError := net.Dial("tcp", "localhost:3000")服务器中使用tcp,因此正在ipv6和ipv4上进行监听。我观察到至少在Windows机器上,该连接为ipv4和ipv6打开了两个连接,然后放弃了ipv6连接,转而支持ipv4。
最后,当TCP连接关闭时,此端口之后将无法立即重用,因为操作系统必须等待TIME_WAIT间隔的持续时间(最大段生命周期,MSL)。
您的客户端代码打开了大量的tcp连接,这些连接的寿命很短,并且取决于您的外围端口范围的范围,您的代码可能崩溃也可能不会崩溃。从16373的数量来看,您具有默认范围。2
>> sysctl net.inet.ip.portrange.first net.inet.ip.portrange.last
net.inet.ip.portrange.first: 49152
net.inet.ip.portrange.last: 65535
Run Code Online (Sandbox Code Playgroud)
最后,
如果要避免由于端口用完而导致崩溃,请执行以下操作:
1.扩大端口的临时范围
。2.使用Docker,容器位于自己的网络上,因此使用一组不同的端口绕过有限的端口范围。
3.在您的客户端代码中引入代码,以每x秒/分钟模拟一次连接
package main
import (
"fmt"
"net"
"time"
)
var count = 0
func testJSON2() string {
return `Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.`
}
func main() {
max := 1000
timer1 := time.NewTicker(5 * time.Second)
i := 0
for range timer1.C {
sendData()
if i == max {
timer1.Stop()
}
i++
}
}
func sendData() {
connection, connectionError := net.Dial("tcp", "localhost:3000")
fmt.Println(connection.LocalAddr())
if connectionError != nil {
fmt.Println(connectionError)
return
}
newmessage := testJSON2()
connection.Write([]byte(newmessage + "\n"))
count++
fmt.Println(count)
err := connection.Close()
if err != nil {
fmt.Println(err)
}
}
Run Code Online (Sandbox Code Playgroud)
参考
^ 1:https : //tip.golang.org/pkg/builtin/#print
^ 2:在Mac上临时端口的范围是多少?
^ 3:https://www.fromdual.com/huge-amount-of-time-wait-connections
小智 1
if connectionError != nil {
fmt.Println(connectionError)
return
}
defer connection.Close()
Run Code Online (Sandbox Code Playgroud)
defer connection.Close() 应该在错误检查之后,因为连接变量可以为零,以防拨号返回时出现一些错误。