【发布时间】:2018-11-05 21:42:01
【问题描述】:
我有一个 Node.js 服务器 + Unity (.NET 3.5) 应用程序,我确保通过套接字进行通信。我在从 Node.js 服务器接收数据到 C# 套接字客户端时遇到问题。
我希望我的 C# 客户端读取套接字流,直到找到换行符 (/n)。这就是我确保数据从 C# 流向 Node.js 服务器的方式,因为有一个名为 split 的 NPM 模块可以确保逐行读取缓冲区。
以下是我的代码,如果您能提出解决方案以实现上述接收数据的方式,我将不胜感激:
在这里,我毫无问题地连接到 Node.js 服务器:
private Socket ClientSocket;
private byte[] _receiveBuffer = new byte[8142];
public string hostname;
public int port;
public void onnectClient()
{
ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ClientSocket.Connect(hostname, port);
ClientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
以下是当前ReceiveCallback,:
private void ReceiveCallback(IAsyncResult AR)
{
int received = ClientSocket.EndReceive(AR);
byte[] recData = new byte[received];
Buffer.BlockCopy(_receiveBuffer, 0, recData, 0, received);
string resultString = System.Text.Encoding.UTF8.GetString(recData);
currentlyReceivedData = JsonUtility.FromJson<ReceivedData>(resultString);
ClientSocket.BeginReceive(_receiveBuffer, 0, _receiveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
更新 1:
现在我使用 TcpClient 和 StreamReader 代替上面的代码,但是由于某种原因,while 循环没有继续:
private void ListenForData()
{
try
{
socketConnection = new TcpClient("localhost", 6670);
Byte[] bytes = new Byte[1024];
while (true)
{
using (StreamReader sr = new StreamReader(socketConnection.GetStream()))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Debug.Log("line");
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
}
【问题讨论】:
-
只是想指出,当您拨打
EndReceive时,不能保证您会一次性收到完整的数据。当完整数据的大小大于缓冲区时,您必须处理 senario,或者由于网络缓慢而仅获取部分数据。 -
SwiftingDuster,这实际上是我猜我的问题!在某些时候,来自 Node.js 服务器的流程只是阻塞,我不再收到任何数据:/