クラスのラッパークラスを作成しています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
に (リスニング ソケット) を に接続する必要がありますか?Client
Server
Client