Last active
August 29, 2021 12:44
-
-
Save petrjahoda/57edc9b2cde43124e1d71da2c97b9897 to your computer and use it in GitHub Desktop.
socket-server
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" | |
"time" | |
) | |
func main() { | |
fmt.Println("Server started...") | |
ln, err := net.Listen("tcp", ":8000") | |
if err != nil { | |
fmt.Println("Error starting socket server: " + err.Error()) | |
} | |
for { | |
conn, err := ln.Accept() | |
if err != nil { | |
fmt.Println("Error listening to client: " + err.Error()) | |
continue | |
} | |
fmt.Println(conn.RemoteAddr().String() + ": client connected") | |
go receiveData(conn) | |
go sendData(conn) | |
} | |
} | |
func sendData(conn net.Conn) { | |
i := 0 | |
for { | |
_, err := fmt.Fprintf(conn, strconv.Itoa(i)+". data from server\n") | |
i++ | |
if err != nil { | |
fmt.Println(conn.RemoteAddr().String() + ": end sending data") | |
return | |
} | |
time.Sleep(time.Duration(1) * time.Second) | |
} | |
} | |
func receiveData(conn net.Conn) { | |
for { | |
message, err := bufio.NewReader(conn).ReadString('\n') | |
if err != nil { | |
fmt.Println(conn.RemoteAddr().String() + ": client disconnected") | |
conn.Close() | |
fmt.Println(conn.RemoteAddr().String() + ": end receiving data") | |
return | |
} | |
fmt.Print(conn.RemoteAddr().String() + ": received " + message) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment