我正在开发一个控制台应用程序,允许客户端将字符串发送到另一个客户端 . 以下是我目前要求的简要说明
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;
}
}
2 回答
问题在于
TcpClient
构造函数的重载(TcpClient(IPEndPoint)
)所以
targetEndPoint
应该是本地 endpoints . 您需要使用重载TcpClient(String, Int32)
来连接到远程的有关更多信息,请参阅TcpClient Class reference on MSDN .
正如@nikolaykondratyev在答案中提到的那样 . 您可以使用
它需要两个参数 -
字符串服务器
int端口号
您可能必须获取活动TCP端口的列表 . 以下是您可以在命令提示符中使用以获取可用端口列表的命令 .