首先。我爲大量的代碼片斷道歉。但在這個階段,我毫無希望,需要一些答案來解決我做錯的事情。使用套接字獲取對象處置異常
我啓動服務器,然後客戶端連接到服務器,然後單擊登錄以驗證其密碼。但事情是。我第一次發送請求時,一切正常,但第一次嘗試後第二次,當我再次按下登錄按鈕時。我得到
拋出異常:「System.ObjectDisposedException」在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.");
}
你是否在服務器端或客戶端獲得此異常? – Tim
該程序不會中斷該問題。但根據我的錯誤handeling。它發生在客戶端 –
然後它發生在服務器也..我打電話跟蹤 –