我在尝试避免使用Thread.sleep(400)
时遇到问题
我的代码是这样的:
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket = Connect(IP, Port);
Thread.Sleep(400);
NetworkStream networkStream = clientSocket.GetStream();
Send(networkStream, "My Data To send");
networkStream.Flush();
和我的send()方法:
public static void Send(NetworkStream networkStream, string Data)
{
int range = 1000;
int datalength = 0;
foreach (string data in Enumerable.Range(0, Data.Length / range).Select(i => Data.Substring(i * range, range)))
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(data);
networkStream.Write(outStream, 0, outStream.Length);
datalength = datalength + range;
Thread.Sleep(50);
}
byte[] LastoutStream = System.Text.Encoding.ASCII.GetBytes(Data.Substring(datalength, Data.Length - datalength) + "$EOS$\r\n");
networkStream.Write(LastoutStream, 0, LastoutStream.Length);
}
Connect方法:
protected static System.Net.Sockets.TcpClient Connect(string Ip, int Onport)
{
//start connection
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
try
{
clientSocket.Connect(Ip, Onport);
}
catch
{
clientSocket.Connect("LocalHost", Onport);
}
return clientSocket;
}
有没有办法检查流是否可以使用?
答案 0 :(得分:2)
虽然您的代码正在运行,但我想指出有关流
的内容 GetStream()
仅在2个案例中返回异常,这些例外情况为(Source):
InvalidOperationException - TcpClient未连接到远程主机。
ObjectDisposedException - TcpClient已关闭。
如果您遇到这两个条件,那么您的信息流应该可用
在代码中编写异常逻辑总是好的,原因与另一方在代码中有错误一样。
在您自己的connect()
方法中,您应该找出异常并通知被调用函数连接失败或将异常抛回调用函数并使用try catch来处理它。因此,在成功的情况下,您将始终获得您的信息流。
try{
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
clientSocket = Connect(IP, Port);
//Thread.Sleep(400);
NetworkStream networkStream = clientSocket.GetStream();
Send(networkStream, "My Data To send");
networkStream.Flush();
}catch(Exception E)
{
//Log
//Its always best to catch the actual exception than general exception
//Handle gracefully
}
Connect Method或者您可以省略异常以回退到来电者
protected static System.Net.Sockets.TcpClient Connect(string Ip, int Onport)
{
//start connection
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
try
{
clientSocket.Connect(Ip, Onport);
}
catch
{
//clientSocket.Connect("LocalHost", Onport);
throw;
}
return clientSocket;
}