简体   繁体   中英

C# Tcpclient Client Send Message To Another client

I'm developing a console App that allow Client To send a string to another Client. Here is the brief of my current requirement
1.) Multiple TcpClient connect to my server using multithread. (Done)
2.) Updating DataBase When Connected. (Done)
2.) Echo message to Client. (Done)
3.) forward message from Client A to Target Client B. Client A need To Pass in 2 parameter which is Message and Target Client Name and i will search in database for IP Address And Port (stucking)

now I'm stucking in forwarding the message to client B which return Error:

"The Request Address Is Not valid In Its Context".

Here is My Code For Sending Message. Function is call within Client A thread.

static bool SendTargetMessage(CommandJson commandJson, Machine machine)
        {
            try
            {
IPAddress targetIP = IPAddress.Parse(machine.machineIP); int targetPort = Convert.ToInt32(machine.machinePort); Console.WriteLine("Target IP : " + targetIP.ToString()); Console.WriteLine("Target Port : " + targetPort); IPEndPoint targetEndPoint = new IPEndPoint(targetIP, targetPort); TcpClient targetClient = new TcpClient(targetEndPoint);

Console.WriteLine("LOL"); if (targetClient.GetStream().CanWrite) { byte[] responseByte = ASCIIEncoding.ASCII.GetBytes(JsonConvert.SerializeObject(commandJson)); targetClient.GetStream().Write(responseByte, 0, responseByte.Length); return true; } else { return false; } } catch (Exception ex) { Console.WriteLine(ex.Message); return false; } }

The problem is in

TcpClient targetClient = new TcpClient(targetEndPoint);

This overload of TcpClient constructor ( TcpClient(IPEndPoint) )

Initializes a new instance of the TcpClient class and binds it to the specified local endpoint.

So targetEndPoint should be local endpoint. You would need to use overload TcpClient(String, Int32) to connect to remote one

Initializes a new instance of the TcpClient class and connects to the specified port on the specified host.

For more information see TcpClient Class reference on MSDN .

As @nikolaykondratyev has mentioned in the answer. You can use

TcpClient client = new TcpClient(server, port);

It takes two parameter-

  • string server
  • int port number

You might have to get a list of active TCP ports. Below is the command you can use in command prompt to get list of available ports.

netstat -a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM