DEV Community

Sadick
Sadick

Posted on • Originally published at Medium on

3 4

Lets make a chat app over telnet

Its completely okay to play with your terminal

The idea is very simple. Build a server and use telnet as a client to relay messages.I have been playing with Go a lot recently and am really enjoying the process.

Well there is only one thing to create, the server to enable telnet communication.

package server
import (
"fmt"
"net"
)
type clients []net.Conn
// stores all the connected clients
var cls clients
// Server represents the ftp server
type Server struct {
Port string
}
// NewServer returns a pointer to a new ftp server
func NewServer(port string) *Server {
return &Server{
Port: port,
}
}
// Run starts a the ftp server
func (s *Server) Run() {
// Resolve the passed port into an address
addrs, err := net.ResolveTCPAddr("tcp", s.Port)
if err != nil {
return
}
// start listening to client connections
listener, err := net.ListenTCP("tcp", addrs)
if err != nil {
fmt.Println(err)
}
// Infinite loop since we dont want the server to shut down
for {
// Accept the incomming connections
conn, err := listener.Accept()
if err != nil {
// continue accepting connection even if an error occurs (if error occurs dont shut down)
continue
}
// add the connection to our client list -cls
cls = append(cls, conn)
// Get the ip the server is running from
ip, err := net.ResolveTCPAddr("tcp", conn.LocalAddr().String())
if err != nil {
fmt.Println("Could not resolve the server IP address")
conn.Close()
}
// write back to the client (telnet connection) on successfull connection
conn.Write([]byte("Connected To " + ip.IP.String() + "\r\n"))
// run it as a go routine to allow multiple clients to connect at the same time
go handleConn(conn)
}
}
func handleConn(conn net.Conn) {
// accept inputs
var buf [512]byte
for {
n, err := conn.Read(buf[0:])
if err != nil {
return
}
for _, v := range cls {
if v.RemoteAddr() != conn.RemoteAddr() {
v.Write([]byte(buf[0:n]))
}
}
fmt.Printf("%s", string(buf[0:n]))
}
}
view raw telnetchat.go hosted with ❤ by GitHub

Usage

package main
import "server"

func main(){
    server.NewServer(":4000")
    server.Run()
}
Enter fullscreen mode Exit fullscreen mode

Suggestions are welcomed. Drop me a line on twitter @izohbiz or leave a comment.

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay