Wednesday, 11 November 2020

golang 14 TCP Server

//cmd -client1
telnet 192.168.0.18 9000
  _l_i_e_n_t_1_
_

//cmd -client2
//client2 connects to server after client 1 connected, can't communicate to server first. After client 1 leaves, communation starts to work
          _c_l_i_e_n_t_2_ _s_t_a_r_t_ _t_o_ _t_y_p_e_

//cmd -server
C:\Users\bob\golang4>go run main.go
client1
can't typeclient2 start to type

----------------------------
//main.go - server
package main

import (
"fmt"
"net"
)

func main() {
ln, err := net.Listen("tcp", ":9000")
if err != nil {
panic(err)
}
defer ln.Close()

for {
conn, err := ln.Accept()
if err != nil {
panic(err)
}

for {
bs := make([]byte, 1024)
n, err := conn.Read(bs)
if err != nil {
break
}

//_, err = conn.Write(bs[:n])
_, err = conn.Write([]byte("_"))
if err != nil {
break
}

fmt.Print(string(bs[:n]))
}

conn.Close()
}
}

No comments:

Post a Comment