Skip to content

Commit

Permalink
Modified port and client name handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Max-X2 committed Oct 15, 2018
1 parent b35dbc7 commit 302716e
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
12 changes: 8 additions & 4 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,18 @@ import (
var exit = make(chan bool)

func main() {
port := ":8080"

fmt.Print("Welcome to TracebookMessenger!\nWhat is your name? : ")
var name string
fmt.Scanln(&name)
fmt.Println(name)


fmt.Println("Type a message and press ENTER to chat.")
// Connect to server socket
conn, _ := net.Dial("tcp", ":8080")
conn, _ := net.Dial("tcp", port)

//send name
fmt.Fprintf(conn, name+"\n")

go sendMessage(conn, name)
go recieveMessage(conn)
Expand All @@ -33,7 +37,7 @@ func sendMessage(c net.Conn, n string) {
input := bufio.NewReader(os.Stdin)
msg, _ := input.ReadString('\n')
// Send to server socket
fmt.Fprintf(c, "( "+n+" ) : "+msg+"\n")
fmt.Fprintf(c, msg+"\n")
}
}

Expand Down
20 changes: 14 additions & 6 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,33 @@ import (
type Client struct {
conn net.Conn
loggedIn bool
name string
}

var clients = []Client{}

func main() {

fmt.Println("Welcome to TracebookMessenger!")
port := ":8080"

ln, _ := net.Listen("tcp", ":8080")
fmt.Println("--------------------------------------------")
fmt.Println("| Welcome to TracebookMessenger! |")
fmt.Println("| Listening for connections on port " + port + " |")
fmt.Println("--------------------------------------------")

ln, _ := net.Listen("tcp", port)

for {
// Accept connection
// Accept connection and grab client name
conn, _ := ln.Accept()
fmt.Println("New Client Connected.")
name, _ := bufio.NewReader(conn).ReadString('\n')
name = name[:len(name)-1] // strips the newline character from input

// Add to list of clients
c := Client{conn, true}
c := Client{conn, true, name}
clients = append(clients, c)

fmt.Println("***New Client Connected : " + c.name)
go c.start()
}
}
Expand All @@ -39,7 +47,7 @@ func (c Client) start() {
msg, _ := bufio.NewReader(c.conn).ReadString('\n')

// Log incomming message
fmt.Print(string(msg))
fmt.Print(string("( " + c.name + " ) : " + msg))

// Echo back to all clients except the sender
for _, client := range clients {
Expand Down

0 comments on commit 302716e

Please sign in to comment.