Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "net"
- "os"
- "time"
- "strconv"
- )
- const (
- CONN_HOST = "localhost"
- CONN_PORT = "3333"
- CONN_TYPE = "tcp"
- )
- func main() {
- // Listen for incoming connections.
- l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
- if err != nil {
- fmt.Println("Error listening:", err.Error())
- os.Exit(1)
- }
- // Close the listener when the application closes.
- defer l.Close()
- fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
- for {
- // Listen for an incoming connection.
- conn, err := l.Accept()
- if err != nil {
- fmt.Println("Error accepting: ", err.Error())
- os.Exit(1)
- }
- // Handle connections in a new goroutine.
- go handleRequest(conn)
- }
- }
- // Handles incoming requests.
- func handleRequest(conn net.Conn) {
- // Make a buffer to hold incoming data.
- for {
- buf := make([]byte, 1024)
- // Read the incoming connection into the buffer.
- len, err := conn.Read(buf)
- if err != nil {
- fmt.Println("Error reading:", err.Error())
- break
- }
- // Send a response back to person contacting us.
- conn.Write([]byte("Message received. " + string(buf[:len])))
- fmt.Printf("%s[% x]\n", buf[:len], buf[:len])
- // Close the connection when you're done with it.
- ticker := time.NewTicker(time.Millisecond * 500)
- go func() {
- sayac := 0
- for t := range ticker.C {
- sayac += 1
- conn.Write([]byte("rutin mesaj. " + strconv.Itoa(sayac) + " " + t.String()))
- }
- }()
- }
- conn.Close()
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement