Last active
August 29, 2021 13:03
-
-
Save petrjahoda/86e179ca9b1b8e1e82771b5998fc07d1 to your computer and use it in GitHub Desktop.
socket-client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"fmt" | |
"net" | |
"strconv" | |
"sync" | |
"time" | |
) | |
var ( | |
connected bool | |
connectedSync sync.Mutex | |
) | |
func main() { | |
fmt.Println("Client started...") | |
for { | |
connectedSync.Lock() | |
alreadyConnected := connected | |
connectedSync.Unlock() | |
if !alreadyConnected { | |
conn, err := net.Dial("tcp", "127.0.0.1:8000") | |
if err != nil { | |
fmt.Println(err.Error()) | |
time.Sleep(time.Duration(5) * time.Second) | |
continue | |
} | |
fmt.Println(conn.RemoteAddr().String() + ": connected") | |
connectedSync.Lock() | |
connected = true | |
connectedSync.Unlock() | |
go sendData(conn) | |
go receiveData(conn) | |
} | |
time.Sleep(time.Duration(5) * time.Second) | |
} | |
} | |
func receiveData(conn net.Conn) { | |
for { | |
message, err := bufio.NewReader(conn).ReadString('\n') | |
if err != nil { | |
fmt.Println(conn.RemoteAddr().String() + ": disconnected") | |
conn.Close() | |
connectedSync.Lock() | |
connected = false | |
connectedSync.Unlock() | |
fmt.Println(conn.RemoteAddr().String() + ": end receiving data") | |
return | |
} | |
fmt.Print(conn.RemoteAddr().String() + ": received " + message) | |
} | |
} | |
func sendData(conn net.Conn) { | |
i := 0 | |
for { | |
_, err := fmt.Fprintf(conn, strconv.Itoa(i)+". data from client\n") | |
i++ | |
if err != nil { | |
fmt.Println(conn.RemoteAddr().String() + ": end sending data") | |
return | |
} | |
time.Sleep(time.Duration(1) * time.Second) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment