0

我正在围绕该类创建一个包装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连接 时ServerClient现在允许向 发送数据Server。但是,当我想接收从我发送的数据时,Server我收到以下错误消息:

不允许发送或接收数据的请求,因为未连接套接字并且(当使用 sendto 调用在数据报套接字上发送时)未提供地址。

我错过了什么?还是做得不对?

在被提示检查是否Server正在侦听后,我查看了我WorkingSocket在包装类中调用的内容,即正在使用的套接字,在成功Server侦听/Client连接协商后检查了这一点。它确实说套接字未连接。所以我现在的问题是:

是否Server需要将(侦听套接字)连接到发送数据,如果您有一个用于多个s Client,您将如何做到这一点?ServerClient

4

1 回答 1

0

一月份我对套接字的工作方式有一个误解。导致该错误是因为我不明白当客户端连接到侦听套接字时,侦听套接字会创建一个新的套接字对象,从客户端发送和接收的所有数据都将链接回该对象。

In my example above I should create and store a new socket for the client to act on, and use this to send and receive data on.

于 2013-03-12T10:56:06.520 回答