Click here to Skip to main content
15,843,727 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I want to connect the Tcp client application to multiple socket listener.
my socket listener is arduino device with esp8266 and it's finished
but i don't know how to use one tcpclient to connect all my socket listener and can send or receive data immediately just send and receive some string like "9L" ,"9H"
hope u guys can help me i'm begin in C#
thanks all

What I have tried:

using System;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading.Tasks;
using System.Threading;


class Program
{
    int port = 80;

    static void Main(string[] args)
    {
        Program program = new Program();
        program.ClientMain();
    }
    public void ClientMain()
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Parse("192.168.4.19"), port);
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        client.Connect(ip);
        new TcpListener(client);
        
    }

   
   
}
public class TcpListener
{
    Thread inThread, outThread;
    NetworkStream stream;
    StreamReader reader;
    StreamWriter writer;
    public TcpListener(Socket client)
    {

        stream = new NetworkStream(client);
        reader = new StreamReader(stream);
        writer = new StreamWriter(stream);
        inThread = new Thread(new ThreadStart(inLoop));
        inThread.Start();
        outThread = new Thread(new ThreadStart(outLoop));
        outThread.Start();        
    }
    public void inLoop()
    {
        while (true)
        {
            String s = reader.ReadLine();
            Console.WriteLine("server:" + s);           
        }
    }

    public void outLoop()
    {
        while (true)
        {            
            writer.WriteLine(Console.ReadLine());
            writer.Flush();            
        }
    }

}
Posted
Updated 5-May-17 4:02am

There is already a tutorial on the site here: [Introduction-to-TCP-client-server-in-C]

If you read the example and make it as the example you should be able to do this in your own code.


goodluck :)
 
Share this answer
 
v3
Comments
Member 13174859 5-May-17 9:02am    
Actually i don't know where i have to set thread inside my code to run the second or more server thanks all
i think you can used
SignalR
[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900