BeginConnect / EndConnect + BeginReceive异常 [英] BeginConnect/EndConnect + BeginReceive Exception

查看:119
本文介绍了BeginConnect / EndConnect + BeginReceive异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨那里!

我在使用c#.Net 3.0的异步套接字时遇到这种奇怪的行为问题是这样的:

我开始连接到tcp使用BeginConnect()的服务器,一旦调用ConnectCallback,我就完成了与EndConnect()的连接。这会触发事件"OnConnected"。

OnConnected的处理程序,接收我刚刚执行EndConnect()的套接字,并立即启动它的BeginReceive()。

现在问题是BeginReceive()抛出了一个异常:

"不允许发送或接收数据的请求,因为套接字没有连接(当使用发送调用在数据报套接字上发送时)没有地址是提供的"

但是,EndConnect()完成没有任何例外?呃,问题是什么。

现在,如果我在创建BeginReceive()之前等待大约5秒钟,那么它工作正常,一个类似的Thread.Sleep(5000)使BeginReceive()工作很好。

我想也许服务器来回发送确认数据,并以某种方式搞砸了?虽然,如果我使用例如java NIO完成端口,那么一切正常并且没有任何延迟。

任何有关这方面的帮助将不胜感激!


解决方案

不确定它有什么帮助,但这里是代码片段的样子:

< code>

//这是BeginConnect方法,尝试连接到服务器
private void BeginConnect()
{
try
{
//设置套接字连接到
_socket = new Socket( AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
_socket.Bind(LocalInetAddress);
//现在开始使用新线程连接到远程
_socket.BeginConnect(_remoteInetAddress,new AsyncCallback( ConnectCallback),this);
}
catch(Exception outerException)
{
//无法设置套接字到远程地址,所以不要打扰尝试

FireOnException(outerException);
}



> //这是BeginConnect的Callback方法
private void ConnectCallback(IAsyncResult ar)
{
if(!IsDisposed)
{
BaseSocketConnection connection = null;
ClientSocketConnector connector = null;

try
{
//获取启动此请求的连接器
connector =(ClientSocketConnector)ar.AsyncState;
//完成并建立连接
connector.Socket.EndConnect(ar);

//设置接收和发送数据包的缓冲区大小
connector.Socket.ReceiveBufferSize = Host.SocketBufferSize;
connector.Socket.SendBufferSize = Host。 SocketBufferSize;

//创建与服务器的新连接
connection = new ClientSocketConnection(Host,this,connector.Socket,ProtocolFactory());
//调试
System.Console .WriteLine("连接到......") + LocalInetAddress);

///////////////////////////问题代码:////////// /////////////////////
////////////////////////// ////////////////////////////////////////////////// ////////////////
//如果我在这里添加BeginReceive ,,,抛出异常
//但是,如果我添加Thread.Sleep(5000);然后一切正常.////connector.Socket.BeginReceive(....);
///////////////////////// ////////////////////////////////////////////////// /////////////////// /////////////////////////// END // /////////////////////////////////////////

//添加连接
AddSocketConnection(connection);
FireOnAccepted(connection);
}
catch(Exception outerException)
{
if(connection!= null)
{
//嗯,我们建立了与遥控器的连接,但仍有一些错误...
//所以断开连接!
try
{
connection.BeginDisconnecting(outerException);
}
catch(Exception innerException)
{
Host.FireOnException(innerException); < br>}



















/代码>结果

Hi There!

I'm getting this strange behaviour when using async sockets with c# .Net 3.0
The problem goes like this:

I start to connect to a tcp server with BeginConnect(), once the ConnectCallback is called, I finish the connection with EndConnect(). This then fires an event "OnConnected".

A handler for OnConnected, receives the socket that I just performed EndConnect() on, and immediately starts BeginReceive() on it.

Now the problem is that BeginReceive() throws me an exception:

"A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a send call) no address was supplied"

But, EndConnect() finished without any exceptions? So eh, what is the problem.

Now, If I wait for about 5 seconds before making the BeginReceive(), then it works just fine, a simble Thread.Sleep(5000) makes the BeginReceive() work fine.

I'm thinking maybe the server is sending acknowledge data back and forth, and somehow fucks things up? Though, if I use for example java NIO completion ports, then everything works fine and there is no delay at all.

Any help on this would be appreciated!


解决方案

Not sure it it helps any, but here is how the code snippets look:

<code>

//This is the BeginConnect method, that tries to connect to the server
private void BeginConnect()
        {
            try
            {
                //Setup the socket to connect to
                _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                _socket.Bind(LocalInetAddress);
                //Now start connecting to the remote with a new thread
                _socket.BeginConnect(_remoteInetAddress, new AsyncCallback(ConnectCallback), this);
            }
            catch (Exception outerException)
            {
                //Failed to setup socket to the remote address, so don't bother trying
                FireOnException(outerException);
            }
        }

//This is the Callback method for BeginConnect
private void ConnectCallback(IAsyncResult ar)
        {
            if (!IsDisposed)
            {
                BaseSocketConnection connection = null;
                ClientSocketConnector connector = null;

                try
                {
                    //Get the connector that started this request
                    connector = (ClientSocketConnector)ar.AsyncState;
                    //Finish and establish the connection
                    connector.Socket.EndConnect(ar);

                    //Set the buffer size for recieving and sending packets
                    connector.Socket.ReceiveBufferSize = Host.SocketBufferSize;
                    connector.Socket.SendBufferSize = Host.SocketBufferSize;

                    //Create a new connection to a server
                    connection = new ClientSocketConnection(Host, this, connector.Socket, ProtocolFactory());
                    //Debugging
                    System.Console.WriteLine("Connected to...     " + LocalInetAddress);

                   ///////////////////////////      PROBLEM CODE: ///////////////////////////////
                   ////////////////////////////////////////////////////////////////////////////////////////////
                   //If I add BeginReceive here,,, the exception is thrown
                   //BUT,  if I add Thread.Sleep(5000); then everything works fine.
                   //connector.Socket.BeginReceive(....);
                   ////////////////////////////////////////////////////////////////////////////////////////////
                   ///////////////////////////      END         ///////////////////////////////////////////

                    //Add the connection
                    AddSocketConnection(connection);
                    FireOnAccepted(connection);
                }
                catch (Exception outerException)
                {
                    if (connection != null)
                    {
                        //Hum, we established a connection to the remote, but still some error...
                        //So disconnect!
                        try
                        {
                            connection.BeginDisconnecting(outerException);
                        }
                        catch (Exception innerException)
                        {
                            Host.FireOnException(innerException);
                        }
                    }
                    else
                    {
                        FireOnException(outerException);
                    }

                }
            }
        }

</code>


这篇关于BeginConnect / EndConnect + BeginReceive异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆