-
-
Save night-codes/683428f933e54ac0883ef37d26920a8f to your computer and use it in GitHub Desktop.
Golang TCP server example
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 server | |
import ( | |
"bufio" | |
"fmt" | |
"log" | |
"net" | |
) | |
// Server ... | |
type Server struct { | |
host string | |
port string | |
} | |
// Client ... | |
type Client struct { | |
conn net.Conn | |
} | |
// Config ... | |
type Config struct { | |
Host string | |
Port string | |
} | |
// New ... | |
func New(config *Config) *Server { | |
return &Server{ | |
host: config.Host, | |
port: config.Port, | |
} | |
} | |
// Run ... | |
func (server *Server) Run() { | |
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%s", server.host, server.port)) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer listener.Close() | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
log.Fatal(err) | |
} | |
client := &Client{ | |
conn: conn, | |
} | |
go client.handleRequest() | |
} | |
} | |
func (client *Client) handleRequest() { | |
reader := bufio.NewReader(client.conn) | |
for { | |
message, err := reader.ReadString('\n') | |
if err != nil { | |
client.conn.Close() | |
return | |
} | |
fmt.Printf("Message incoming: %s", string(message)) | |
client.conn.Write([]byte("Message received.\n")) | |
} | |
} |
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 server | |
import ( | |
"testing" | |
) | |
func TestServer(t *testing.T) { | |
server := New(&Config{ | |
Host: "localhost", | |
Port: "3333", | |
}) | |
server.Run() | |
} | |
// echo "hello world" | nc localhost 3333 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment