I am new in Go and I am trying to create a server which can receive a message from a client and send it to other client or any other specific client. I have tried many chat examples but what I wanted to do is to create two files where one is for server and another is for the client. This is the code I tried so far.
server.go
package main
import "net"
import "fmt"
import "bufio"
import "strings"
func send(c net.Conn){
netData, err := bufio.NewReader(c).ReadString('
')
if err != nil {
fmt.Println(err)
return
}
temp := strings.TrimSpace(string(netData))
fmt.Printf(temp)
}
func main() {
fmt.Println("Launching server...")
// listen on all interfaces
ln, _ := net.Listen("tcp", ":8081")
for {
// Listen for an incoming connection.
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error accepting: ", err.Error())
continue
}
go send(conn)
}
client.go
package main
import "net"
import "fmt"
import "bufio"
import "os"
func recieve(conn net.Conn){
message, _ := bufio.NewReader(conn).ReadString('
')
fmt.Println(message)
}
func send(conn net.Conn){
reader := bufio.NewReader(os.Stdin)
text, _ := reader.ReadString('
')
fmt.Fprintf(conn, text)
}
func main(){
// connect to this socket
conn, err := net.Dial("tcp", "127.0.0.1:8081")
if err != nil {
fmt.Println("Error accepting: ", err.Error())
}
for {
go recieve(conn)
go send(conn)
}
conn.Close()
}
When I try to run that my computer crashed. I understand I am making some mistake for handling the send & received message but couldn't able to figure it out. I will appreciate any kind of help. Thanks.