我正在围绕该类创建一个包装Socket
类。
我有一个执行此操作的连接异步回调:
public void StartConnecting()
{
// Connect to a remote device.
try
{
//_acceptIncomingData = acceptIncomingData;
// Create a TCP/IP socket.
_workingSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
if (Information != null)
Information(this, new InfoEventArgs("Connecting", "Working socket is initiating connection"));
// Connect to the remote endpoint.
_workingSocket.BeginConnect(_localEndPoint,
new AsyncCallback(ConnectCallback), _workingSocket);
}
catch (Exception ex)
{
if (Error != null)
Error(this, new ErrorEventArgs(ex.Message, ex));
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
// ACTION CONNECTED COMPLETE
if (Information != null)
Information(this, new InfoEventArgs("Connected", "Working socket has now connected"));
// Start Receiving on the socket
// Create the state object.
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 ex)
{
if (Error != null)
Error(this, new ErrorEventArgs(ex.Message, ex));
}
}
对于状态对象,它使用预定义的类:
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
我用它来连接一个已经开始监听的套接字,我称这个监听套接字为Server
,它使用Socket
类。上面的代码是一个我称之为Client
. 当Client
连接 时Server
,Client
现在允许向 发送数据Server
。但是,当我想接收从我发送的数据时,Server
我收到以下错误消息:
不允许发送或接收数据的请求,因为未连接套接字并且(当使用 sendto 调用在数据报套接字上发送时)未提供地址。
我错过了什么?还是做得不对?
在被提示检查是否Server
正在侦听后,我查看了我WorkingSocket
在包装类中调用的内容,即正在使用的套接字,在成功Server
侦听/Client
连接协商后检查了这一点。它确实说套接字未连接。所以我现在的问题是:
是否Server
需要将(侦听套接字)连接到发送数据,如果您有一个用于多个s Client
,您将如何做到这一点?Server
Client