我正在开发以学习为目的的小程序。
我的程序是简单的 Telnet 控制台。
我使用 visual studio 2010 Express 创建了非常酷的 UI,现在我正在尝试与远程服务器(Creston 控制处理器)建立通信。我从 this Microsoft article 复制并粘贴了类(class)当我执行类(class)时,程序卡住了。我不确定如何正确描述发生的情况,但在基本词中所有控件(包括关闭按钮)都停止工作。
这是我类(class)的代码:(我添加了一些调试行);
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
public string TempString = string.Empty;
public int TotalBytesRead = 0;
public char[] charBuffer = new char[1000];
}
public class AsynchronousClient
{
// The port number for the remote device.
private const int port = 23;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
public AsynchronousClient()
{
}
public void New()
{
StartClient();
}
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("10.106.6.60"), port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Console.WriteLine("StartSend");
// Send test data to the remote device.
//Send(client, "hostname\n");
//sendDone.WaitOne();
Console.WriteLine("WaitForResponse");
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Read From Socket : {0}", response);
Console.WriteLine("ReleaseSocket");
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
Console.WriteLine("Receive");
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
Console.WriteLine("Start Read");
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
Console.WriteLine("Bytes read: {0}", bytesRead);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
string tsTempString = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
state.TempString += tsTempString;
Console.WriteLine("String {0}", tsTempString);
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
Console.WriteLine("Send");
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Console.WriteLine("SendCallBack");
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
当连接到服务器时,它会响应以下几行:
CP3 Console
Warning: Another console session is open
CP3>
当我运行程序时,我得到以下输出:
Socket connected to 10.106.6.60:23
StartSend
WaitForResponse
Receive
Start Read
Bytes read: 13
String CP3 Console
Start Read
Bytes read: 43
String Warning: Another console session is open
Start Read
Bytes read: 6
String
CP3>
The thread '<No Name>' (0x1d80) has exited with code 0 (0x0).
The thread '<No Name>' (0x24bc) has exited with code 0 (0x0).
我尝试了不同的读取流的方法,但都没有成功。程序仍然卡在同一个地方。
似乎在读取最后一个字节“>”后程序没有重新执行方法“ReceiveCallback”以退出循环。
我感觉它与调用“ReceiveCallback”的方式有关,但我无法弄清楚 client.beginReceive() 参数的实际作用。
最佳答案
进一步阐述 Roemer 的回答:EndReceive
只有在对话终止时才会返回 0。这通常意味着已收到带有 FIN 或 RST 标志的 TCP 数据包,最常见的原因是对等方(在您的情况下为服务器)关闭其端点或退出。 (还有各种其他情况;例如,防火墙或中间节点可能会生成 RST。)
(Roemer 写道“BeginReceive never returns zero...”,但显然是指 EndReceive
,因为 BeginReceive
返回 IAsyncResult
对象。)
如果对方没有结束对话,EndReceive
将不会返回 0,您将永远不会进入回调的 else
分支调用 receiveDone.Set()
。
从您的描述中并不能完全清楚服务器的行为方式,但它最后发送的 6 个字节显然是一个换行符,后跟“CP3>”提示符。那时它正在等待您的客户发送一些东西。它不会关闭连接。
TCP 是一种字节流服务——它不提供记录边界。所以套接字层无法知道服务器何时“发送完毕”,除非服务器关闭连接。您为客户提供三种选择:
- 在您收到服务器的输出时对其进行解析并识别它何时等待输入(在本例中,这意味着识别“CP3>”提示)
- 在任意时间过去且没有来自服务器的进一步数据后,确定服务器已完成
- 别管它,只需在收到数据时从服务器输出数据即可
第三个选项是最简单的一个。建立连接后执行第一个 BeginReceive
。然后,在您的回调方法中,如果对话仍处于打开状态且未发生错误,则处理您收到的数据并再次调用 BeginReceive
。
关于c# - 套接字读取卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30130414/