客户端未及时收到消息(TcpClient)
本文关键字:消息 TcpClient 客户端 | 更新日期: 2023-09-27 18:01:41
我有两个应用程序通过Tcp相互"交谈",问题是当我发送一些东西时,应用程序不会同时接收它,只有当他第二次请求时,然后'他'接收它重复。例如:
客户端请求连接(income string: 00200001 0050);
服务器接受连接(确认)(输出字符串:00570002);
客户端没有收到确认,但是当他再次请求连接时,它收到一个输出字符串:00570002 00570002 (duplicate)。
这在任何连接到我的应用程序中都会发生。
private int listenerPort = 4545;
private TcpListener listener;
private TcpClient socket;
public Communicator()
{
try
{
this.listener = new TcpListener(IPAddress.Parse("127.0.0.1"), listenerPort);
listenerPort++;
listener.Start();
this.connectToPendingRequest();
}
catch (Exception ex)
{
listener.Stop();
throw new Exception(ex.Message);
}
}
/// <summary>
/// Try to connect to any pending requests
/// </summary>
public void connectToPendingRequest()
{
try
{
if (socket == null || !socket.Connected)
if (listener.Pending())
{
this.socket = Listener.AcceptTcpClient();
this.socket.NoDelay = true;
}
}
catch (InvalidOperationException) { throw new Exception("Listener was not started!"); }
catch (Exception ex) { throw new Exception("Error has ocurred when connecting to device: " + ex.Message); }
}
/// <summary>
/// Send messages to Device
/// </summary>
public void sendMessages(string stringMessage)
{
if (socket.Connected)
{
try
{
byte[] outStream = Encoding.ASCII.GetBytes(stringMessage);
socket.GetStream().Write(outStream, 0, outStream.Length);
socket.GetStream().Flush();
}
catch (Exception ex)
{
throw new Exception("Message could not be sent.'nError: " + ex.Message);
}
}
else { throw new Exception("No device connected"); }
}
/// <summary>
/// Get Message From socket
/// </summary>
/// <returns></returns>
public String getMessageFromSocket()
{
try
{
byte[] inStream = new byte[10025];
socket.GetStream().Read(inStream, 0, (int)socket.ReceiveBufferSize);
return System.Text.Encoding.ASCII.GetString(inStream);
}
catch (Exception ex)
{
throw new Exception("Message could not be read.'nError: " + ex.Message);
}
}
我忘了什么吗?它是否有办法确保消息已经到达?(我猜tcp应该这样做,但是…)
Ps:我在接收消息时没有问题。
提前感谢!
-
listenerPort++;
不需要。多个客户端可以连接到相同端口上的相同侦听器 - 我在这里没有看到客户端代码或者它与服务器代码纠缠在一起
- socket.GetStream(). flush()不需要。
- .Pending()是非阻塞的,所以你可以错过连接时刻 查看tcpplistener和TcpClient代码示例
下面是一个使用Read()返回值的快速示例:
/// <summary>
/// Get Message From socket
/// </summary>
/// <returns></returns>
public String getMessageFromSocket()
{
try
{
byte[] inStream = new byte[10025];
int bytesRead = socket.GetStream().Read(inStream, 0, inStream.Length);
return System.Text.Encoding.ASCII.GetString(inStream, 0, bytesRead);
}
catch (Exception ex)
{
throw new Exception("Message could not be read.'nError: " + ex.Message);
}
}
但是,不要忽视Scott Chamberlain给你的伟大建议。这根本无法帮助您解决更大的问题,即确定何时接收到完整的"消息"。