Created
October 24, 2022 06:07
-
-
Save abhijit-hota/42c0d8914acb32c670c7471be75fa3b1 to your computer and use it in GitHub Desktop.
TCP Server & Client
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bufio" | |
"errors" | |
"fmt" | |
"log" | |
"net" | |
"os" | |
"strings" | |
) | |
const thisAddr = "10.22.20.129" | |
func main() { | |
fmt.Println("Hello. This is your IP to share: ", thisAddr) | |
fmt.Print("Wait for someone or start a connection? ([w]/s) ") | |
ans := "" | |
if n, err := fmt.Scanln(&ans); err != nil && n != 0 { | |
log.Fatal(err) | |
} | |
switch strings.TrimSpace(ans) { | |
case "w", "": | |
waitForConnections(thisAddr) | |
case "s": | |
fmt.Print("IP of the computer? ") | |
ip, err := scanIPV4() | |
if err != nil { | |
log.Fatal(err) | |
} | |
connectToIP(ip) | |
default: | |
log.Fatal("invalid") | |
} | |
} | |
func waitForConnections(thisAddr string) { | |
l, err := net.Listen("tcp", thisAddr+":1289") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer l.Close() | |
fmt.Println("Waiting for someone to join...") | |
conn, err := l.Accept() | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer conn.Close() | |
fmt.Println("Connection established: ", conn.RemoteAddr().String()) | |
go receive(conn) | |
send(conn) | |
} | |
func connectToIP(ip string) { | |
conn, err := net.Dial("tcp", net.JoinHostPort(ip, "1289")) | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer conn.Close() | |
fmt.Println("\nConnection established: ", conn.RemoteAddr().String()) | |
go receive(conn) | |
send(conn) | |
} | |
func receive(conn net.Conn) { | |
buf := bufio.NewReader(conn) | |
for { | |
data, err := buf.ReadString('\n') | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("\b\b\b\b\b\b\b\b[them]:\t%s\n[you]:\t", strings.TrimSpace(data)) | |
} | |
} | |
func send(conn net.Conn) { | |
s := bufio.NewScanner(os.Stdin) | |
for { | |
fmt.Print("[you]:\t") | |
msg, err := scanStr(s) | |
if err != nil { | |
log.Fatal(err) | |
} | |
if _, err := conn.Write([]byte(msg)); err != nil { | |
log.Fatal(err) | |
} | |
} | |
} | |
func scanStr(s *bufio.Scanner) (string, error) { | |
if s.Scan() { | |
return s.Text(), nil | |
} | |
err := s.Err() | |
return "", err | |
} | |
func scanIPV4() (ip string, err error) { | |
s := bufio.NewScanner(os.Stdin) | |
if s.Scan() { | |
ip, err = s.Text(), nil | |
} | |
err = s.Err() | |
if err != nil { | |
return | |
} | |
res := net.ParseIP(ip) | |
if res == nil { | |
err = &net.ParseError{} | |
return | |
} | |
ip = res.To4().String() | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment