我正在开发一个允许客户端将字符串发送到另一个客户端的控制台应用程序。
以下是我目前要求的简要说明
1.)多个TcpClient使用多线程连接到我的服务器。 (完成)
2.)连接时更新数据库。 (完成)
2.)向客户发送回复消息。 (完成)
3.)从客户端A转发到目标客户端的消息B.客户端A需要传入2个参数,即消息和目标客户端名称,我将在数据库中搜索IP地址和端口(卡住)
现在我仍然坚持将消息转发给客户端B,返回错误:
"请求地址在其上下文中无效"。
这是我发送消息的代码。函数是在客户端A线程中调用。
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; } }
答案 0 :(得分:0)
问题在于
TcpClient targetClient = new TcpClient(targetEndPoint);
TcpClient
构造函数(TcpClient(IPEndPoint)
)
初始化TcpClient类的新实例并将其绑定到指定的本地端点。
因此targetEndPoint
应该是本地端点。您需要使用重载TcpClient(String, Int32)
来连接到远程
初始化TcpClient类的新实例并连接到指定主机上的指定端口。
有关详细信息,请参阅TcpClient Class reference on MSDN。
答案 1 :(得分:0)
正如@nikolaykondratyev在答案中提到的那样。你可以使用
TcpClient client = new TcpClient(server, port);
需要两个参数 -
您可能必须获取活动TCP端口列表。下面是您可以在命令提示符中使用的命令,以获取可用端口列表。
netstat -a