Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: close network connection #317

Merged
merged 1 commit into from
Dec 9, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions content/chapter 5/5.2-tcp-server-begginer.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,6 @@ func (s *Server) start() error {
if err != nil {
return err
}
defer ln.Close()
// مقدار دهی listener
s.ln = ln
// با تابع acceptLoop اتصال های جدید به سرور را مدیریت میکنیم
Expand All @@ -64,6 +63,13 @@ func (s *Server) start() error {
return nil
}

// اینجا برای استاپ کردن سرور یک متد جدید تعریف میکنیم
func (s *Server) stop() {
if s.ln != nil {
s.ln.Close()
}
}

func (s *Server) acceptLoop() {
for {
// اتصال های موجود را تایید میکنیم متغییر conn را با اتصال مورد نظر مقدار دهی میکنیم
Expand Down Expand Up @@ -104,16 +110,21 @@ func (s *Server) readLoop(conn net.Conn) {
func main() {
// ساخت سرور
server := newServer(":3000")

//start the server
if err := server.start(); err != nil {
log.Fetal(err)
}

go func() {
// در ازای هر پیام مقادیر آن را چاپ میکنیم
for msg := range server.msgch {
fmt.Printf("recived new from connection(%s): %s\n", msg.from, msg.payload)
}
}()
// شروع سرور
log.Fatal(server.start())

// Run an infinite loop to keep the program running
select {}

}

Expand Down
Loading