我的系统与某个服务器连接。我正在从服务器上读取数据。 但我想从服务器不断读取数据。 这是我的代码:
TcpClient client = new TcpClient("169.254.74.65", 7998);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[1024];
String responseData = String.Empty;
Int32 bytes = stream.Read(data, 0, data.Length);
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
stream.Close();
client.Close();
有人能告诉我在哪里放置while循环以便能够连续收听?
答案 0 :(得分:0)
要持续接收数据,您实际上需要进行一些循环。
例如:
private void StartProcessing(Socket serverSocket)
{
var clientSocket = serverSocket.Accept();
StartReceiveing(clientSocket);
}
private void StartReceiveing(Socket clientSocket)
{
const int maxBufferSize = 1024;
try
{
while (true)
{
var buffer = new byte[maxBufferSize];
var bytesRead = clientSocket.Receive(buffer);
if (ClientIsConnected(clientSocket))
{
var actualData = new byte[bytesRead];
Array.Copy(buffer, actualData, bytesRead);
OnDataReceived(actualData);
}
else
{
OnDisconnected(clientSocket);
}
}
}
catch (SocketException ex)
{
Console.WriteLine(ex.Message);
}
}
private void OnDisconnected(Socket issuedSocket)
{
if (issuedSocket != null)
{
issuedSocket.Shutdown(SocketShutdown.Both);
issuedSocket.Close();
StartProcessing(listener);
}
}
private void OnDataReceived(byte[] data)
{
//do cool things
}
private static bool ClientIsConnected(Socket socket)
{
return !(socket.Poll(1000, SelectMode.SelectRead) && socket.Available == 0);
}
答案 1 :(得分:0)
只需在不更改代码的情况下添加循环:
TcpClient client = new TcpClient("169.254.74.65", 7998);
NetworkStream stream = client.GetStream();
Byte[] data = new Byte[1024];
String responseData = String.Empty;
Int32 bytes;
while(true) {
bytes = stream.Read(data, 0, data.Length);
if (bytes > 0) {
responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
Console.WriteLine("Received: {0}", responseData);
}
}
stream.Close();
client.Close();
这样它将无限地从主线程中的服务器请求数据。 其他改进可能是: