我正在研究用于学习目的的小程序。
我的程序是简单的Telnet控制台。
现在,我使用Visual Studio 2010 Express创建了非常酷的UI,我试图与远程服务器(Creston控制处理器)建立通信。我从this Microsoft article复制并粘贴了类,当我执行该类时,程序冻结了。我不确定如何正确地描述会发生什么,但是用基本的词来说,所有控件(包括关闭按钮)都停止工作。
这是我类(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永远不会返回零...”,但明确地表示EndReceive
,因为BeginReceive
返回IAsyncResult
对象。)
如果对等方没有结束对话,则EndReceive
不会返回0,并且您将永远不会进入调用else
的回调的receiveDone.Set()
分支。
从您的描述中还不能完全清楚服务器的运行方式,但是最后发送的6个字节显然是换行符,后跟“CP3>”提示。那时,它正在等待您的客户发送一些东西。它不会关闭连接。
TCP是字节流服务-它不提供记录边界。因此,套接字层无法知道服务器何时“完成发送”,除非服务器关闭连接。您可以为客户提供三种选择:
第三种选择是最简单的选择。建立连接后,请执行第一个
BeginReceive
。然后,在您的回调方法中,如果对话仍然打开并且没有发生错误,请处理您收到的数据并再次调用BeginReceive
。关于c# - 套接字读取卡住,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30130414/