gpt4 book ai didi

c# - 使用套接字获取对象处置异常

转载 作者:行者123 更新时间:2023-12-03 11:51:44 26 4
gpt4 key购买 nike

首先。对于大量的代码段,我深表歉意。但是我现阶段绝望了,需要对我做错的事情做出一些回答。

我启动服务器,然后客户端连接到服务器,然后单击登录以验证其密码。但是事实是。第一次发送请求时,一切运行正常,但是第二次在第一次尝试后,再次按下登录按钮时,一切正常。我懂了

Exception thrown: 'System.ObjectDisposedException' in System.dll



我似乎无法弄清楚我的问题在哪里。

我还需要帮助,以确保我必须断开用户和所有内部存储设备的连接。

代码 :
    private byte[] _buffer = new byte[16 * 1024];
static List<Socket> _connectedClients = new List<Socket>();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
private IPEndPoint ipport = null;
private int port = 0;


private void SetupServer()
{
lstConnections.Items.Add("--==( Setting Up Server )==--");
_serverSocket.Bind(ipport);
_serverSocket.Listen(38);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}

private void AcceptCallback(IAsyncResult AR)
{
Socket socket;
try
{
//socket = (Socket)AR.AsyncState;
socket = _serverSocket.EndAccept(AR);
}
catch (ObjectDisposedException)
{

return;
}

_connectedClients.Add(socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), socket);
Invoke((MethodInvoker)delegate { lstConnections.Items.Add("Client Connected, Waiting for request..."); });
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}

private void RecieveCallback(IAsyncResult AR)
{
try
{
Socket socket = (Socket)AR.AsyncState;
int recieved = 0;
try
{
recieved = socket.EndReceive(AR);

}
catch (Exception exc)
{
FileHandlerTxt FHandler = new FileHandlerTxt();
FHandler.appendDataToTextFile(new List<string> { string.Format("Client forcefully disconnected at {0}. Error : {1}", DateTime.UtcNow.ToLongDateString(), exc.Message) });
socket.Close();
_connectedClients.Remove(socket);
return;
}

byte[] dataBuffer = new byte[recieved];
Array.Copy(_buffer, dataBuffer, recieved);

object unkown = dataBuffer.Deserialize();

if (unkown is Login)
{
Invoke((MethodInvoker)delegate { lstConnections.Items.Add("Got login request..."); });
#region Login
Login login = (Login)unkown;

//Do stuff in the call Class
// .Serialize() is an extension method

byte[] data = call.Serialize();
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), socket);
Invoke((MethodInvoker)delegate { lstConnections.Items.Add(login.Username + " Signed in"); });
}
else
{
MessageClass call = new MessageClass("Failed. Password incorrect");
call.ckey = 2;
login.updateFailedAttempts(LoginAttempts + 1);
byte[] data = call.Serialize();
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), socket);
}
}
else
{
MessageClass call = new MessageClass("Failed. To many failed attempts");
call.ckey = 4;
RootObject LocData = LocationData.getLocationData();
string message = string.Format("You have entered your password wrong 3 times on {0} at {1} from {2}:{3}. Your account has been locked. Please go to the lodge to unlock your account.", DateTime.UtcNow.ToLongDateString(), DateTime.UtcNow.ToLongTimeString(), IPLocation.getIPAddress(), LocData.country);
message.SendEmail();
byte[] data = call.Serialize();
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), socket);
}

}
else
{
MessageClass call = new MessageClass("Failed. User does not exists");
call.ckey = 3;
byte[] data = call.Serialize();
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(RecieveCallback), socket);
}
#endregion
}
else if (unkown is Client)
{
#region Client
Client newClient = (Client)unkown;
newClient.Queries(newClient.ckey);
Invoke((MethodInvoker)delegate
{
lstConnections.Items.Add("Did requested Client query");
});

#endregion
}
else if (unkown is MessageClass)
{
Invoke((MethodInvoker)delegate { lstConnections.Items.Add("Got Disconnect request..."); });
MessageClass call = (MessageClass)unkown;
if (call.ckey == -10)
{
socket.Shutdown(SocketShutdown.Both);
socket.Close();
socket.Dispose();
_connectedClients.Remove(socket);
Invoke((MethodInvoker)delegate { lstConnections.Items.Add("Client Disconnected..."); });
return;
}
}


}
catch (Exception exc)
{
FileHandlerTxt FHandler = new FileHandlerTxt();
FHandler.appendDataToTextFile(new List<string> { string.Format("RecieveCallback problem at {0}. Error : {1}", DateTime.UtcNow.ToLongDateString(), exc.Message) });
}


}



private void SendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}

然后是客户端。
再一次,我希望它做对了:
private void btnSignIn_Click(object sender, RoutedEventArgs e)
{



//Enable wat onder is vir Authentication

try
{

Login login = new Login(txtUsername.Text,passboxPassword.SecurePassword.EncryptPassword(txtUsername.Text),IPLocation.getIPAddress(),0);
_clientSocket.Connect(new IPEndPoint(IPAddress.Parse("192.168.1.14"),8081));
_clientSocket.Send(login.Serialize());
RecieveResponse();
}
catch (SocketException se)
{
FileHandlerTxt FHandler = new FileHandlerTxt();
FHandler.appendDataToTextFile(new List<string> { string.Format("Socket Exception {0} on {1}", se.Message, DateTime.UtcNow.ToLongDateString()) });
}
catch (Exception exc)
{
FileHandlerTxt FHandler = new FileHandlerTxt();
FHandler.appendDataToTextFile(new List<string> { string.Format("Exception {0} on {1}", exc.Message, DateTime.UtcNow.ToLongDateString()) });
}



}


private void RecieveResponse()
{
byte[] buffer = new byte[2048];
int recieved = _clientSocket.Receive(buffer, SocketFlags.None);
if (recieved == 0) return;
byte[] data = new byte[recieved];
Array.Copy(buffer,data,recieved);
object unkown = data.Deserialize();
MessageClass returnMessage = (MessageClass)unkown;
if (returnMessage.ckey == 1)
{
string AskingPasscode = "";
RecievePasscode passauth = new RecievePasscode();
if (passauth.ShowDialog() == false)
{
AskingPasscode = passauth.PassCode;
}
if (AskingPasscode == returnMessage.PassKey.DecryptPasscode(txtUsername.Text))
{
if (returnMessage.AuthLevel == 2)
{
SESSION.AccountType = "Admin";
SESSION.AuthLevel = 2;
SESSION.ID = returnMessage.client.ID;
SESSION.Name = returnMessage.client.Name;
MainWindow main = new MainWindow();
main.Show();
this.Close();
}
else if (returnMessage.AuthLevel == 1)
{
SESSION.AccountType = "Hunter";
SESSION.AuthLevel = 1;
SESSION.ID = returnMessage.client.ID;
SESSION.Name = returnMessage.client.Name;
MainWindow main = new MainWindow();
main.Show();
this.Close();
}
else
{
SESSION.AccountType = "User";
SESSION.AuthLevel = 0;
SESSION.ID = returnMessage.client.ID;
SESSION.Name = returnMessage.client.Name;
MainWindow main = new MainWindow();
main.Show();
this.Close();
}
}
}
else
{
MessageBox.Show(returnMessage.Message);
}

MessageClass call = new MessageClass("Exit");
call.ckey = -10;
_clientSocket.Send(call.Serialize());
_clientSocket.Shutdown(SocketShutdown.Both);
_clientSocket.Close();
_clientSocket.Dispose();
MessageBox.Show("Client Disconnect.");


}

最佳答案

在客户端,您正在_clientSocket中放置RecieveResponse,但是_clientSocket似乎已被下一步按钮btnSignIn_Click所重用。这肯定会导致ObjectDisposedException
您每次都需要创建一个新的套接字。

关于c# - 使用套接字获取对象处置异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42590193/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com