Advertisement
Guest User

Untitled

a guest
Sep 25th, 2016
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "fmt"
  5. "net"
  6. "os"
  7. "time"
  8. "strconv"
  9. )
  10.  
  11. const (
  12. CONN_HOST = "localhost"
  13. CONN_PORT = "3333"
  14. CONN_TYPE = "tcp"
  15. )
  16.  
  17. func main() {
  18. // Listen for incoming connections.
  19. l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
  20. if err != nil {
  21. fmt.Println("Error listening:", err.Error())
  22. os.Exit(1)
  23. }
  24. // Close the listener when the application closes.
  25. defer l.Close()
  26. fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
  27. for {
  28. // Listen for an incoming connection.
  29. conn, err := l.Accept()
  30. if err != nil {
  31. fmt.Println("Error accepting: ", err.Error())
  32. os.Exit(1)
  33. }
  34. // Handle connections in a new goroutine.
  35. go handleRequest(conn)
  36. }
  37. }
  38.  
  39. // Handles incoming requests.
  40. func handleRequest(conn net.Conn) {
  41. // Make a buffer to hold incoming data.
  42. for {
  43. buf := make([]byte, 1024)
  44. // Read the incoming connection into the buffer.
  45. len, err := conn.Read(buf)
  46. if err != nil {
  47. fmt.Println("Error reading:", err.Error())
  48. break
  49. }
  50. // Send a response back to person contacting us.
  51. conn.Write([]byte("Message received. " + string(buf[:len])))
  52. fmt.Printf("%s[% x]\n", buf[:len], buf[:len])
  53. // Close the connection when you're done with it.
  54. ticker := time.NewTicker(time.Millisecond * 500)
  55. go func() {
  56. sayac := 0
  57. for t := range ticker.C {
  58. sayac += 1
  59. conn.Write([]byte("rutin mesaj. " + strconv.Itoa(sayac) + " " + t.String()))
  60. }
  61. }()
  62. }
  63.  
  64. conn.Close()
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement