TCPClient将消息发送到2个服务器位置

TCPClient将消息发送到2个服务器位置

本文介绍了TCPClient将消息发送到2个服务器位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 

以下是MSDN示例中的简单连接和发送消息功能。我正在尝试向2个不同的服务器发送消息。

是否还需要做其他事情才能从第一个服务器消息中释放本地端口,以便第二个服务器可以收到消息? / p>

我的测试显示第二台服务器没有收到消息。在我开始对服务器进行故障排除之前,我只是希望有更多TCPClient经验的人确定代码应该正常工作,并且没有任何特殊的处理来自同一应用程序的2服务器消息。

 Shared Sub Connect(服务器为[String],消息为[String])
尝试
'创建一个TcpClient。
'注意,要使此客户端工作,您需要将TcpServer
'连接到服务器指定的相同地址,端口
'组合。
Dim port As Int32 = 13000
Dim client As New TcpClient(server,port)

'将传递的消息转换为ASCII并将其存储为Byte数组。
Dim data As [Byte]()= System.Text.Encoding.ASCII.GetBytes(message)

'获取用于读写的客户端流。
'Stream stream = client.GetStream();
Dim stream As NetworkStream = client.GetStream()

'将消息发送到连接的TcpServer。
stream.Write(data,0,data.Length)

Console.WriteLine(" Sent:{0}",message)

'关闭一切。
stream.Close()
client.Close()
Catch e As ArgumentNullException
Console.WriteLine(" ArgumentNullException:{0}",e)
捕获e作为SocketException
Console.WriteLine(" SocketException:{0}",e)
结束尝试

Console.WriteLine(ControlChars.Cr +"按Enter键继续......")
Console.Read()
结束子'连接


解决方案


Below is a simple connect and send message function from the MSDN sample. I'm trying to send a message to 2 different servers.

Is there something else that needs to be done to release the local port from the first server message so that the 2nd server can receive a message?

My testing shows that the 2nd server is not getting the message. Before I start troubleshooting the server I just want someone with more experience with TCPClient to concure that the code should work fine and there isn't anything special for handling 2 server message from same application.

Shared Sub Connect(server As [String], message As [String])
   Try 
      ' Create a TcpClient. 
      ' Note, for this client to work you need to have a TcpServer  
      ' connected to the same address as specified by the server, port 
      ' combination. 
      Dim port As Int32 = 13000
      Dim client As New TcpClient(server, port)

      ' Translate the passed message into ASCII and store it as a Byte array. 
      Dim data As [Byte]() = System.Text.Encoding.ASCII.GetBytes(message)

      ' Get a client stream for reading and writing. 
      '  Stream stream = client.GetStream(); 
      Dim stream As NetworkStream = client.GetStream()

      ' Send the message to the connected TcpServer. 
      stream.Write(data, 0, data.Length)

      Console.WriteLine("Sent: {0}", message)

      ' Close everything.
      stream.Close()
      client.Close()
   Catch e As ArgumentNullException
      Console.WriteLine("ArgumentNullException: {0}", e)
   Catch e As SocketException
      Console.WriteLine("SocketException: {0}", e)
   End Try

   Console.WriteLine(ControlChars.Cr + " Press Enter to continue...")
   Console.Read()
End Sub 'Connect


解决方案


这篇关于TCPClient将消息发送到2个服务器位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 00:16