客户端刷新连接上的C#套接字错误代码10054
我一直在尝试为我正在构建的应用程序编写一个利用TCP的通信层。我控制服务器端和客户端操作 我遇到的问题是,当我使用“localhost”作为我的IP时,我没有任何问题。然而,当我使用互联网连接时,一切都会神奇地工作……第一次。当客户机尝试构建到服务器的另一个套接字连接时,我在ReadCallback期间,特别是在执行socket.EndReceive操作时,在服务器端得到SocketException错误代码10054 我已经看到了我的套接字没有得到正确处理的可能性——它们确实应该得到正确处理,因为我看不到客户端或服务器端应用程序的路径不会导致关闭 我的代码与MSDN中的代码非常相似,可以在 以下是我的客户代码的相关部分:客户端刷新连接上的C#套接字错误代码10054,c#,.net,sockets,asynchronous,C#,.net,Sockets,Asynchronous,我一直在尝试为我正在构建的应用程序编写一个利用TCP的通信层。我控制服务器端和客户端操作 我遇到的问题是,当我使用“localhost”作为我的IP时,我没有任何问题。然而,当我使用互联网连接时,一切都会神奇地工作……第一次。当客户机尝试构建到服务器的另一个套接字连接时,我在ReadCallback期间,特别是在执行socket.EndReceive操作时,在服务器端得到SocketException错误代码10054 我已经看到了我的套接字没有得到正确处理的可能性——它们确实应该得到正确处理,
public class ClientStateObject
{
// Client socket.
public Socket workSocket = null;
// Receive buffer.
public byte[] buffer = new byte[Constants.ClientBuffer];
// Received data string.
public StringBuilder sb = new StringBuilder();
public List<byte[]> Data = new List<byte[]>();
}
public class AsynchronousClient
{
// 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 byte[] response = null;
public static object StartClient(object sendObj)
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is ...
IPHostEntry ipHostInfo = Dns.Resolve(Constants.Hostname); // localhost
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, Constants.Port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
LingerOption lo = new LingerOption(false, 0);
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
// Send test data to the remote device.
object[] s;
s = new object[2] { sendObj, "<EOF>" };
Send(client, s);
sendDone.WaitOne();
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Response received : {0}", response);
//Console.ReadKey();
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
//object res = Deserialize(Deserialize(response) as byte[]);
object res = Deserialize(Deserialize(response) as byte[]);
return res;
}
catch (Exception e)
{
return e;
}
}
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.
ClientStateObject state = new ClientStateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, Constants.ClientBuffer, 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.
ClientStateObject state = (ClientStateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
state.Data.Add(state.buffer); // Concat byte[] to received packet
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, Constants.ClientBuffer, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = ConcatByteListToArray(state.Data);
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static byte[] ConcatByteListToArray(List<byte[]> b)
{
List<byte> bList = new List<byte>();
foreach (byte[] bA in b)
{
foreach (byte by in bA)
{
bList.Add(by);
}
}
return bList.ToArray();
}
private static void Send(Socket client, object data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Serialize(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
{
// 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());
}
}
/*
* Function: Serialize(object obj)
* Requires: Arbitrary object.
* Returns: MyMessage object, which constants a byte[] (Data) representing an object in TCP-friendly form.
* Description: Private function used to turn an object into a serialized byte[].
*/
private static byte[] Serialize(object obj)
{
using (var memoryStream = new MemoryStream())
{
(new BinaryFormatter()).Serialize(memoryStream, obj);
return memoryStream.ToArray();
}
}
/*
* Function: Deserialize(MyMessage message)
* Requires: MyMessage object with Data attribute.
* Returns: object which was originally serialized.
* Description: Private function used to reverse the process of "Serialize".
*/
private static object Deserialize(byte[] message)
{
using (var memoryStream = new MemoryStream(message))
{
return (new BinaryFormatter()).Deserialize(memoryStream);
}
}
公共类ClientStateObject
{
//客户端套接字。
公共套接字工作组=null;
//接收缓冲区。
公共字节[]缓冲区=新字节[Constants.ClientBuffer];
//接收到的数据字符串。
公共StringBuilder sb=新StringBuilder();
公共列表数据=新列表();
}
公共类异步客户端
{
//ManualResetEvent实例信号完成。
专用静态手动重置事件已完成=
新手动重置事件(错误);
私有静态手动重置事件sendDone=
新手动重置事件(错误);
私有静态手动重置事件接收完成=
新手动重置事件(错误);
//来自远程设备的响应。
私有静态字节[]响应=null;
公共静态对象StartClient(对象sendObj)
{
//连接到远程设备。
尝试
{
//为套接字建立远程端点。
//名称
//远程设备是。。。
IPHostEntry ipHostInfo=Dns.Resolve(Constants.Hostname);//localhost
IPAddress IPAddress=ipHostInfo.AddressList[0];
IPEndPoint remoteEP=新IPEndPoint(ipAddress,Constants.Port);
//创建TCP/IP套接字。
套接字客户端=新套接字(AddressFamily.InterNetwork,
流,ProtocolType.Tcp);
Lingroption lo=新的Lingroption(假,0);
client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.Linger,lo);
//连接到远程端点。
client.BeginConnect(remoteEP,
新的异步回调(ConnectCallback),客户端);
connectDone.WaitOne();
//将测试数据发送到远程设备。
对象[]s;
s=新对象[2]{sendObj,“};
发送(客户机);
sendDone.WaitOne();
//从远程设备接收响应。
接收(客户);
receiveDone.WaitOne();
//将响应写入控制台。
WriteLine(“收到的响应:{0}”,响应);
//Console.ReadKey();
//松开插座。
client.Shutdown(SocketShutdown.Both);
client.Close();
//object res=反序列化(反序列化(响应)为字节[]);
object res=反序列化(反序列化(响应)为字节[]);
返回res;
}
捕获(例外e)
{
返回e;
}
}
专用静态无效连接回调(IAsyncResult ar)
{
尝试
{
//从状态对象检索套接字。
套接字客户端=(套接字)ar.AsyncState;
//完成连接。
客户端.EndConnect(ar);
WriteLine(“连接到{0}的套接字”,
client.RemoteEndPoint.ToString());
//表示已建立连接的信号。
connectDone.Set();
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
私有静态void接收(套接字客户端)
{
尝试
{
//创建状态对象。
ClientStateObject状态=新ClientStateObject();
state.workSocket=客户端;
//开始从远程设备接收数据。
client.BeginReceive(state.buffer,0,Constants.ClientBuffer,0,
新建异步回调(ReceiveCallback),状态);
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
私有静态void ReceiveCallback(IAsyncResult ar)
{
尝试
{
//检索状态对象和客户端套接字
//从异步状态对象。
ClientStateObject状态=(ClientStateObject)ar.AsyncState;
套接字客户端=state.workSocket;
//从远程设备读取数据。
int bytesRead=client.EndReceive(ar);
如果(字节读取>0)
{
//可能会有更多数据,因此请存储到目前为止收到的数据。
state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead));
state.Data.Add(state.buffer);//将字节[]添加到接收的数据包中
//获取其余的数据。
client.BeginReceive(state.buffer,0,Constants.ClientBuffer,0,
新建异步回调(ReceiveCallback),状态);
}
其他的
{
//所有数据都已到达,请将其作为响应。
如果(说明长度>1)
{
响应=concatbytelistotarray(state.Data);
}
//表示已接收到所有字节的信号。
receiveDone.Set();
}
}
捕获(例外e)
{
Console.WriteLine(如ToString());
}
}
专用静态字节[]Con
public class ServerStateObject
{
// Client socket.
public Socket workSocket = null;
// Receive buffer.
public byte[] buffer = new byte[Constants.ServerBuffer];
// Received data string.
public StringBuilder sb = new StringBuilder();
public List<byte[]> Data = new List<byte[]>();
}
public class AsynchronousSocketListener
{
public static bool GetDataSuccess;
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[Constants.ServerBuffer];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, Constants.Port);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
LingerOption lo = new LingerOption(false, 0);
listener.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lo);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
//Console.WriteLine("Done waiting for client.");
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
ServerStateObject state = new ServerStateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, Constants.ServerBuffer, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
ServerStateObject state = (ServerStateObject)ar.AsyncState;
Socket handler = state.workSocket;
Console.WriteLine("Read {0} bytes from {1} : {2}.",
content.Length, (handler.LocalEndPoint as IPEndPoint).Address, (handler.LocalEndPoint as IPEndPoint).Port);
int bytesRead = 0;
try
{
bytesRead = handler.EndReceive(ar);
}
catch (SocketException se)
{
Console.WriteLine("Socket Exception in Callback Read: {0}", se.ErrorCode); // I always get an error here on refresh
}
// Read data from the client socket.
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead)); // Check if there is an EOF in the byte[]
state.Data.Add(state.buffer); // Concat byte[] to received packet
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
byte[] rArray = ConcatByteListToArray(state.Data);
byte[] sendArray = Serialize(HandleRead(rArray));
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from {1} : {2}.",
content.Length, (handler.LocalEndPoint as IPEndPoint).Address, (handler.LocalEndPoint as IPEndPoint).Port);
// Echo the data back to the client.
Send(handler, sendArray);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, Constants.ServerBuffer, 0,
new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, object data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Serialize(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
Console.WriteLine("Connection to client broken.");
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
connectDone.Reset();
sendDone.Reset();
receiveDone.Reset();