Last active
September 30, 2016 11:51
-
-
Save sadick254/fc91c1bb1d218759affd9911134d32e7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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])) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment