Commit 487bcda2 authored by Sushant Mahajan's avatar Sushant Mahajan

initial chat client server working (not using gob)

parent fb0580cf
package main package main
import ( import (
"bufio"
"fmt" "fmt"
"net" "net"
"os" "os"
"bufio"
"encoding/gob"
) )
func client() { func main() {
conn, err := net.Dial("tcp", "localhost:5000") conn, err := net.Dial("tcp", "localhost:5000")
//defer conn.Close()
if err != nil { if err != nil {
fmt.Println("Err:", err) fmt.Println("Err:", err)
return
} }
reader := bufio.NewReader(os.Stdin) reader := bufio.NewReader(os.Stdin)
for { for {
msg, _ := reader.ReadString('\n') msg, err := reader.ReadString('\n')
fmt.Println(msg)
err = gob.NewEncoder(conn).Encode(msg)
if err != nil { if err != nil {
fmt.Println("Err:", err) fmt.Println("Err: ", err)
} }
fmt.Println(msg)
conn.Write([]byte(msg))
} }
}
func main() { conn.Close()
go client()
var input string
fmt.Scanln(&input)
} }
...@@ -2,8 +2,8 @@ package main ...@@ -2,8 +2,8 @@ package main
import ( import (
"fmt" "fmt"
"encoding/gob"
"net" "net"
"bytes"
) )
func startServer() { func startServer() {
...@@ -26,13 +26,17 @@ func startServer() { ...@@ -26,13 +26,17 @@ func startServer() {
} }
func handleClient(conn net.Conn) { func handleClient(conn net.Conn) {
//defer conn.Close()
var msg string
for { for {
err := gob.NewDecoder(conn).Decode(&msg) buf := make([]byte, 1024)
_, err := conn.Read(buf)
if err != nil { if err != nil {
//fmt.Println("Err: ", err) fmt.Println("Err: ", err)
} else { }
n := bytes.Index(buf, []byte{0})
if n != 0 {
msg := string(buf[:n-1])
fmt.Println("Received: ", msg) fmt.Println("Received: ", msg)
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment