Show chat room content to new connected user - TCP server

I have this TCP server:

package main

import (

func main()  {

	ln, err := net.Listen("tcp", ":8094")
	if err != nil {

	aconns := make(map[net.Conn]int)
	conns := make(chan net.Conn)
	dconns := make(chan net.Conn)
	msgs := make(chan string)
	i := 0

	go func() {
		for {
			conn, err := ln.Accept()
			if err != nil {
			conns <- conn

	for {

		select {
		//read incoming messages
		case conn := <-conns:
			aconns[conn] = i
			//once we have the conection, read from it
			go func(conn net.Conn, i int) {

				rd := bufio.NewReader(conn)
				for {
					m, err := rd.ReadString('\n')
					if err != nil {
					msgs <- fmt.Sprintf("client %v: %v", i, m)
				//done reading
				dconns <- conn
			}(conn, i)

		case msg := <- msgs:
			//broadcast to all connections
			for conn:= range aconns{

		case dconn := <-dconns:
			log.Printf("client %v is gone\n", aconns[dconn])
			delete(aconns, dconn)

Consider there are 3 clients chatting with eachother and another client comes in. How can I show previous texts to the new user? Is it doable?


I haven’t look at your code super closely, but what I have looked at appears to write every incoming message to every connection then forget about it. As a result when a new user connect you have no way to tell them about old messages because your server doesn’t know what they were anymore.

There are many ways to handle this, but your best bet is probably to pick a number of messages you want to remember (maybe start with the last 10 messages?) and keep a buffer of them. You will have to think through the problem and figure out how to create a buffer that can be read by your new connection goroutine (so it can send a new user the last 10 messages when they connect), and then can be updated whenever someone posts a new message. Once you take a stab at implementing I’m happy to answer any specific questions or help out, but I won’t post a solution just yet so you can learn by doing :slight_smile:

1 Like

Thank you. I will do that.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.