2016-05-31 214 views
-1

我正在开发一个控制台应用程序,允许客户端将字符串发送到另一个客户端。 这里是我当前需求的简要
1.)多个TcpClient使用多线程连接到我的服务器。 (完成)
2.)连接时更新数据库。 (完成)
2.)向客户回复消息。 (完成)
3.)从客户端A转发消息到目标客户端B.客户端A需要传递2参数,它是消息和目标客户端名称,我将在数据库中搜索IP地址和端口(填充)C#Tcpclient客户端发送消息到另一个客户端

现在我将消息转发给客户端B正在stucking它会返回错误:

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

这里是我的代码发送消息。函数在Client 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

从'machine.machineIP'检查IP,可能是IP地址无效。也尝试获取发生错误的特定行。 – NikolayKondratyev

+0

该ip是正确的,该错误发生在TcpClient targetClient = new TcpClient(targetEndPoint); –

回答

0

的问题是在

TcpClient targetClient = new TcpClient(targetEndPoint); 

TcpClient构造(TcpClient(IPEndPoint))的此重载

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

所以targetEndPoint应该当地端点。您将需要使用过载TcpClient(String, Int32)连接到远程一个

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

欲了解更多信息,请参阅TcpClient Class reference on MSDN

+0

我已经解决了这个问题。我不需要创建一个到目标客户端的新连接,因为这也需要客户端的监听器,我所做的是将所有可用的连接存储在字典中,并且我可以使用连接将消息转发到目标客户端。感谢您的回复。现在即时通讯解决了另一个问题,即发送速度太快时,发送的数据将连接在一起并导致错误。 –

0

正如@nikolaykondratyev在答案中提到的。您可以使用

TcpClient client = new TcpClient(server, port); 

它需要两个参数 -

  • 字符串服务器
  • INT端口号

你可能必须得到活动的TCP端口的列表。以下是您可以在命令提示符中使用的命令获取可用端口列表的命令。

netstat -a 
+0

感谢您的回复。我已经通过添加字典中的所有可用连接来解决该问题,并且我可以将消息转发到字典中的任何连接。现在即时通讯解决了另一个问题,即发送速度太快时,发送的数据将连接在一起并导致错误。 –

相关问题