4

I am new to go, I was trying to prepare client server in go language and tried to write code, but it's not giving any output. It's not giving any error but just listening.

Please someone help me, I want to create authentication system using go where server authenticate client using Username password..

server :

package main

import (
        "fmt"
        "net"
)

func main() {
        service := "0.0.0.0:8080"
        tcpAddr, err := net.ResolveTCPAddr("tcp", service)
        checkError(err)
        listener, err := net.ListenTCP("tcp", tcpAddr)
        checkError(err)
        for {
                conn, err := listener.Accept()
                //fmt.Println("Server listerning")
                _, err = conn.Read([]byte("HEAD"))
                if err != nil {
                        conn.Close()
                }
                if err != nil {
                        continue
                }
        }
}

func checkError(err error) {
        if err != nil {
                fmt.Println("Fatal error ", err.Error())
        }
}

client :

package main

import (
        "bufio"
        "fmt"
        "net"
        "os"
        "strings"
)

func main() {
        if len(os.Args) != 2 {
                fmt.Println("Usage: ", os.Args[0], "host")
                os.Exit(1)
        }
        host := os.Args[1]
        conn, err := net.Dial("tcp", host+":8080")
        checkError(err)
        _, err = conn.Write([]byte("HEAD"))
        reader := bufio.NewReader(os.Stdin)
        for {
                line, err := reader.ReadString('\n')
                ftm.Println(err)
                line = strings.TrimRight(line, " \t\r\n")
                if err != nil {
                        conn.Close()
                        break

                }
        }
}
func checkError(err error) {
        if err != nil {
                fmt.Println("Fatal error ", err.Error())
        }
}
zzzz
  • 87,403
  • 16
  • 175
  • 139
  • The `checkError` function basically prints the error and then does nothing. This is wrong on itself, and its name is therefore misleading. Consider using `log.Fatal(err)` which prints the error and calls `os.Exit(1)`. Or add such a call to `os.Exit` to your error-handling function and rename it to `die` or something like this. – kostix Dec 11 '12 at 08:13
  • Don't forget that at one point you'll want to close your connection even if there isn't an error `defer conn.close()` should be outside and after the brackets, and the first error clause should be above the read - I know this is a few years later but incase people read this. – Jono Feb 22 '15 at 17:59

2 Answers2

5

I'm not sure you need to resolve your address in order to listen.

You should be able to do just this :

listener, err := net.Listen("tcp", ":8080")

And you don't seem to do anything with the received bytes server side (you discard the result of Read), which explains why you think you receive nothing.

Note that your code can only handle one connection at a time. You should handle each opened connection in a new goroutine.

Here's an example of client-server communication over TCP in a related question.

Community
  • 1
  • 1
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • After making that change i run : go run fs.go so it's giving error : # command-line-arguments .\fs.go:10: cannot use ":8080" (type string) as type *net.TCPAddr in function ar gument –  Nov 30 '12 at 12:02
  • Sorry : the function to use is Listen, not ListenTCP. I edited. Listen calls ListenTCP internally. – Denys Séguret Nov 30 '12 at 12:05
  • Ok, can you please give me any other example other then http://stackoverflow.com/questions/11202058/unable-to-send-gob-data-over-tcp-in-go-programming/11202252#11202252 –  Nov 30 '12 at 13:01
  • @KarimkhanPathan What part is missing ? What's blocking you ? – Denys Séguret Nov 30 '12 at 13:05
  • dear really dont know, when I run above program both of them keep listening. I am getting what wrong there... –  Nov 30 '12 at 13:37
  • 3
    @KarimkhanPathan I think the example given above is what you need. Since you will need to send structured data (username/password; authentication results; etc.) other than arbitrary strings, you do need encoder and decoder. And with encoder/decoder, you don't have to deal with bufio. Just use Encode() and Decode() method. If you wanna interface with other language and don't want to use Gob, simple replace Gob with Json, XML or something. – Song Gao Dec 01 '12 at 03:48
  • I was making mistake in listening the port. Did in this way : listener, err := net.Listen("tcp", ":8080") in proper way and place. Which solved the problem –  Jul 05 '13 at 03:38
2

I'm not sure exactly what output your expecting, as it seems to me that you are not printing anything out, just reading input in the client. As @dystroy pointed out, the server then discards what it received, only checking for errors in the communication.

Also, it seems that your server should just sit there listening, as you have it in a loop doing just that. If you look in the docs for the net package, it gives an example of how to run a server and client. Here's a sample that I made from that, that worked for me.

Server:

ln, err := net.Listen("tcp", ":8080")
// handle error
for {
    conn, err := ln.Accept()
    // handle error
    var cmd []byte
    fmt.Fscan(conn, &cmd)
    fmt.Println("Message:", string(cmd))
}

Client:

conn, err := net.Dial("tcp", "127.0.0.1:8080")
// handle error
fmt.Fprintf(conn, "message\n")

Edited to add: The expected result of this program is that you run the server and it sits waiting. You then run the client in a different terminal, which immediately exits, but now the server has printed "Message: message". If you run the client again, the server will print the same message again. I tested this code on my machine (just adding code to respond to errors) and it worked as advertised.

Derek
  • 3,087
  • 1
  • 21
  • 23