“ Socket.Receive”功能后,套接字丢失连接

时间:2019-06-21 16:11:17

标签: c# sockets

我有一个c#客户端。客户端的任务是登录到服务器。

问题是: 当我要登录时,我使用一个TCP套接字,该套接字在初始化“ wpf”窗口时创建。使用套接字一次发送数据后,一切正常,但是当我想使用同一套接字再次发送数据时,会弹出此异常:

System.ObjectDisposedException:'无法访问已处置的对象。 对象名称:“ System.Net.Sockets.Socket”。

经过一些测试,我发现问题是由Socket.Receive函数引起的。我在调用函数之前检查了套接字,并且套接字已连接(Socket.Connected == true),从函数返回后,套接字未连接(Socket.Connected == false)

private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
// Get host related information.
IPHostEntry hostEntry = Dns.GetHostEntry(server);

// Loop through the AddressList to obtain the supported AddressFamily.
foreach (IPAddress address in hostEntry.AddressList)
{       
    //attempting to connect.
    IPEndPoint ipe = new IPEndPoint(address, port);
            //making a temp socket to check the connection (if something went wronge/ the server isnt active)
            Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        // attempting connection.
        tempSocket.Connect(ipe);
            }
            catch (Exception)
            {
                Console.WriteLine("Request timed out");
            }

            //if we connected to the server, we are ok to continue.
            if (tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            //else the connection isnt successful (the server might not respond) we need to try again.
            else
            {
                continue;
            }
}
Globals.SOCKET = s;
return s;
}

//This func will send a request to the server and returns the server's response.
public static string SocketSendReceive(string server, int port, string request, Socket socket = null)
{
    Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
    Byte[] bytesReceived = new Byte[256];
    string response = "";
    // Create a socket connection with the specified server and port.
    if (socket == null)
        socket = ConnectSocket(server, port);
    using (socket)
    {
        // If the connection faild and couldnt maintain a socket.
               if (socket.Connected == false)
            return ("Connection failed");

        // Send request to the server.
        socket.Send(bytesSent, bytesSent.Length, 0);

                // Receiving the packet from the server.
                int bytes = socket.Receive(bytesReceived, bytesReceived.Length,0);//***The problem occures Here***
               response = response + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
    }
    return response;
}

第二个功能是从服务器发送和接收数据的功能。 第一个只是连接并创建一个套接字

感谢您的帮助! -安东尼

1 个答案:

答案 0 :(得分:0)

更改

socket.Receive(bytesReceived,bytesReceived.Length,0)

收件人

socket.Receive(bytesReceived,0,bytesReceived.Length)