Multithreaded TCP server [SOLVED]

Hey there… Where can I find a muti-threaded TCP server example? I searched on the net but I only found basics example with only one client…

[EDIT]

I found the following code, but when I connect 2 or more clients, when some client send some string, server broadcasts this received message to everyone. How can I do to not broadcasting and reply only the client who sent that message? Below the code I found;

package main

import (
	"bufio"
	"fmt"
	"net"
)

var allClients map[*Client]int

type Client struct {
	// incoming chan string
	outgoing   chan string
	reader     *bufio.Reader
	writer     *bufio.Writer
	conn       net.Conn
	connection *Client
}

func (client *Client) Read() {
	for {
		line, err := client.reader.ReadString('\n')
		if err == nil {
			if client.connection != nil {
				client.connection.outgoing <- line
			}
			fmt.Println(line)
		} else {
			break
		}

	}

	client.conn.Close()
	delete(allClients, client)
	if client.connection != nil {
		client.connection.connection = nil
	}
	client = nil
}

func (client *Client) Write() {
	for data := range client.outgoing {
		client.writer.WriteString(data)
		client.writer.Flush()
	}
}

func (client *Client) Listen() {
	go client.Read()
	go client.Write()
}

func NewClient(connection net.Conn) *Client {
	writer := bufio.NewWriter(connection)
	reader := bufio.NewReader(connection)

	client := &Client{
		// incoming: make(chan string),
		outgoing: make(chan string),
		conn:     connection,
		reader:   reader,
		writer:   writer,
	}
	client.Listen()

	return client
}

func main() {
	allClients = make(map[*Client]int)
	listener, _ := net.Listen("tcp", ":2007")
	for {
		conn, err := listener.Accept()
		if err != nil {
			fmt.Println(err.Error())
		}
		client := NewClient(conn)
		for clientList, _ := range allClients {
			if clientList.connection == nil {
				client.connection = clientList
				clientList.connection = client
				fmt.Println("Connected")
			}
		}
		allClients[client] = 1
		fmt.Println(len(allClients))
	}
}

Tnx.

1 Like

up

Hi,

Have a look at the example in the standard library, it’s a basic server that echoes back what a client connection sends to it.
Example Listener

Pieter

1 Like

Thanks but that example does not work on my situation, I need a multi client example.

I think I need to clarify exactly what you mean by multi client.

The example shows a TCP server that can handle more than one client at a time, isn’t that what you need?

Here’s some more info and examples:
TCP Sockets: Network Programming in Go

Chat server example
Go: Code that grows with grace

1 Like

go servers are multi client. i guess you need to know who sent a request to properly respond it.
maybe this example help:

package main

import (
	"fmt"
	"net"
	"os"
)

const (
	CONN_HOST = ""
	CONN_PORT = "3333"
	CONN_TYPE = "tcp"
)

func main() {
	// Listen for incoming connections.
	l, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
	if err != nil {
		fmt.Println("Error listening:", err.Error())
		os.Exit(1)
	}
	// Close the listener when the application closes.
	defer l.Close()
	fmt.Println("Listening on " + CONN_HOST + ":" + CONN_PORT)
	for {
		// Listen for an incoming connection.
		conn, err := l.Accept()
		if err != nil {
			fmt.Println("Error accepting: ", err.Error())
			os.Exit(1)
		}
		// Handle connections in a new goroutine.
		go handleRequest(conn)
	}
}

// Handles incoming requests.
func handleRequest(conn net.Conn) {
	// Make a buffer to hold incoming data.
	buf := make([]byte, 1024)
	// Read the incoming connection into the buffer.
	_, err := conn.Read(buf)
	if err != nil {
		fmt.Println("Error reading:", err.Error())
	}
	fmt.Println(conn.RemoteAddr())
	// Send a response back to person contacting us.
	conn.Write([]byte("Message received."))
	// Close the connection when you're done with it.
	conn.Close()
}

i changed line 46 to get the ip of the sender.

3 Likes

This is a simple TCP Server I’ve implemented & used in some projects (with some small customizations).

1 Like

This problem has been already fixed.I’m getting an EOF problem shown at the end of this topic;

If anyone knows a way to fix it…

Tnx.

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