首页 > 解决方案 > “Socket.Receive”函数后套接字丢失连接

问题描述

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

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

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;
}

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

谢谢你的帮助!-安东尼

标签: c#sockets

解决方案


改变

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

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


推荐阅读