package main import ( "bufio" "fmt" "net" "os" "strconv" "strings" "time" ) // Prints the messages received directly to the console // If it is a server PING, reply the correct PONG func printMesages(connection net.Conn) { reader := bufio.NewReader(connection) for { message,err := reader.ReadString('\n') if err != nil { fmt.Printf("Error while reading") fmt.Println(err.Error()) return } fmt.Print(message) fields := strings.Fields(message) for index := range fields { if fields[index] == "PING" { fmt.Fprintf(connection,"PONG %s\n",fields[index+1]) } } } } func main() { var serverAdress string var serverPort int if len(os.Args) > 2 { serverAdress = os.Args[1] var err error serverPort, err = strconv.Atoi(os.Args[2]) if err != nil { fmt.Println("Port cannot be parsed to int!") fmt.Println(err.Error()) os.Exit(-1) } } else { fmt.Println("Usage : GoIRC [Server address] [Server port]") os.Exit(-1) } fmt.Printf("Trying to connect to %s:%d ...\n", serverAdress, serverPort) connection, err := net.Dial("tcp",fmt.Sprintf("%s:%d",serverAdress,serverPort)) if err != nil { fmt.Println("Error while trying to connect to the server!") fmt.Println(err.Error()) os.Exit(-1) } // On exit, quit the server and close the connection defer connection.Close() defer fmt.Fprintf(connection,"quit\n") fmt.Println("Connected !") go printMesages(connection) time.Sleep(1 * time.Second) // ID ourselves to the server _, err = fmt.Fprintf(connection,"nick goTrot\nuser goTrot 0 * :trotFunky\n") if err != nil { fmt.Println(err.Error()) os.Exit(-1) } // Wait for ident response to pass time.Sleep(10 * time.Second) // Now we can join a channel and start speaking fmt.Fprintf(connection, "join #trot_go_test\n") fmt.Fprintf(connection, "privmsg #trot_go_test :BONJOUR MÉCRÉANT\n") time.Sleep(10 * time.Second) }