This project is a simple TCP server implementation written in Go.
It demonstrates how to create a server that listens on a TCP port, accepts multiple client connections, and reads messages sent by connected clients.
- Listens for incoming TCP connections on a specified port.
- Accepts multiple client connections concurrently using goroutines.
- Reads messages from clients and sends them to a central message channel.
- Logs all received messages.
- Graceful shutdown through a quit channel.
serverstruct: Holds the server configuration including listener, quit channel, and message channel.newServer: Constructor function to initialize a new server instance.Start: Starts the server, listens for connections, and begins accepting clients.acceptLoop: Continuously accepts new client connections and starts areadLoopfor each.readLoop: Handles reading data from each client connection and forwards it to the message channel.main: Creates and starts the server on port3000, logging all incoming messages.
- Go 1.18 or higher
git clone https://github.com/yourusername/tcp-server-go.git
cd tcp-server-gogo run main.goBy default, the server listens on port 3000.
- Start the server.
- Use a TCP client such as
telnetornc(netcat) to connect:nc localhost 3000
- Type a message and press Enter.
- The server will display the received message in the terminal.
Terminal 1: Start the server
go run main.goTerminal 2: Connect as a client
nc localhost 3000Output on server side
new connection to the server: 127.0.0.1:54321
hello server
received msg from connection hello server
- The server currently runs indefinitely until stopped manually.
- Messages from disconnected clients are ignored, but the server continues accepting new connections.