WPF客户端服务器登录应用程序,C#源代码 [英] WPF Client Server Login Application, C# source code
问题描述
大家好
我已经在WPF中创建了一个客户端/服务器登录应用程序.当我执行服务器应用程序时,它将等待客户端连接,然后当我执行客户端应用程序并尝试输入密码,然后单击登录按钮时,出现错误提示...
System.NullReferenceException ..
我对此WPF感到困惑,对我来说还很陌生,如果有人可以帮助我,我会非常感激
这是 Server 类的代码...
Hello Everyone
I have created a Client / Server Login application in WPF. When I execute the server application it waits for the client to connect, then when I execute the Client application and I try to enter the password and I click the login button it gives me an error saying...
System.NullReferenceException..
I''m stuck and im very new to this WPF, If someone can help me on this I would appritiated a lot
This is the Code for Server class...
<pre lang="msil">using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Timers;
using System.Threading;
using System.Net.Sockets;
using System.IO;
using System.Windows.Threading;
using System.Collections;
using System.ComponentModel;
using System.Windows.Controls.Primitives;
namespace DtposServer
{
// This stores data about each client ClientData
public struct ClientData
{
public Socket structSocket;
public Thread structThread;
}
/// <summary>
/// Interaction logic for TCPServer.xaml
/// </summary>
public partial class TCPServer : Window
{
private System.Timers.Timer clockTimer;
//===================================\\
private StatusBar statusBar1 = new StatusBar();
private TcpListener tcpLsn;
private Hashtable ht = new Hashtable();
private static Int32 connectId = 0;
private Thread tcpThd;
private string ipAddress = "0.0.0.0";
//private System.ComponentModel.IContainer components;
public TCPServer()
{
InitializeComponent();
clockTimer = new System.Timers.Timer(1000);
clockTimer.Elapsed += new ElapsedEventHandler(clockTimer_Elapsed);
clockTimer.Start();
DataContext = this;
// ============================================================ \\
tcpLsn = new TcpListener(System.Net.IPAddress.Parse(ipAddress), 8000);
tcpLsn.Start();
txtBlock1.Text = "IP Address listen at: " + " " + tcpLsn.LocalEndpoint.ToString();
tcpThd = new Thread(WaitingForClient);
tcpThd.Start();
}
void clockTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Dispatcher.BeginInvoke(new Action(UpdateCurrentDateTime));
}
#region " Server Waiting For Client To Connect "
// Waiting For Client
public void WaitingForClient()
{
ClientData CData = default(ClientData);
while (true)
{
// Accept will block until someone connects
CData.structSocket = tcpLsn.AcceptSocket();
Interlocked.Increment(ref connectId);
CData.structThread = new Thread(ReadSocket);
lock (this)
{
//It is used to keep connected Sockets and active thread
ht.Add(connectId, CData);
updateDataGrid(("Connection accepted."));
updateDataGrid(("Connected User: > " + connectId + " Time: " + DateTime.Now.ToLongTimeString()));
updateDataGrid(("---------------------------------------------"));
}
CData.structThread.Start();
}
}
#endregion
#region " Server Read Socket When Client Connects "
//Read Socket
public void ReadSocket()
{
//Real-Id will not be changed for each thread, but connectId is
//changed. It can not be used to delete object from Hashtable
Int32 realId = connectId;
Byte[] receive = null;
ClientData cd = (ClientData)dataHolder(realId);
Socket s = cd.structSocket;
int ret = 0;
while (true)
{
if (s.Connected)
{
receive = new Byte[100];
try
{
//Receive will block until data coming ret is 0 or Exception
//will happen when Socket connection is broken
ret = s.Receive(receive, receive.Length, 0);
if (ret > 0)
{
//ClientData clntData = new ClientData();
foreach (ClientData clntData in ht.Values)
{
if (clntData.structSocket.Connected)
{
clntData.structSocket.Send(receive, ret, SocketFlags.None);
}
}
}
else
{
break; // TODO: might not be correct. Was : Exit While
}
}
catch (Exception e)
{
updateDataGrid(e.ToString());
if (!s.Connected)
{
break; // TODO: might not be correct. Was : Exit While
}
}
}
}
CloseTheThread(realId);
}
#endregion
#region " Server Closing The Thread "
// Close The Thread
private void CloseTheThread(long realId)
{
try
{
ClientData cd = (ClientData)dataHolder(realId);
cd.structThread.Abort();
}
catch (Exception)
{
lock (this)
{
ht.Remove(realId);
updateDataGrid(("Disconnected User: > " + realId + " Time: " + DateTime.Now.ToLongTimeString()));
}
}
}
private ClientData dataHolder(long realId)
{
throw new NotImplementedException();
}
#endregion
#region " Server Updating The Data Grid "
// Update Data Grid
public void updateDataGrid(string displayString)
{
txtServerConnection.AppendText((displayString)); // + ControlChars.Cr + ControlChars.Lf));
}
#endregion
[BrowsableAttribute(false)]
public static bool CheckForIllegalCrossThreadCalls { get; set; }
private void TCPSerever_Loaded(object sender, RoutedEventArgs e)
{
CanvasBorder.BorderThickness = new Thickness(1);
lblDate.Content += DateTime.Today.DayOfWeek + ", " + DateTime.Now.ToLongDateString();
//This is a snippet to hold the control of the illegal Cross-Thread call operation
CheckForIllegalCrossThreadCalls = false;
//===============================================
txtServerConnection.Text = "Wating for connection... ";
}
public string CurrentDateTime
{
get { return (string)GetValue(CurrentDateTimeProperty); }
set { SetValue(CurrentDateTimeProperty, value); }
}
public static readonly DependencyProperty CurrentDateTimeProperty =
DependencyProperty.Register("CurrentDateTime", typeof(string), typeof(TCPServer), new UIPropertyMetadata(string.Empty));
private void UpdateCurrentDateTime()
{
CurrentDateTime = DateTime.Now.ToShortTimeString();
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
if ((tcpLsn != null))
{
tcpLsn.Stop();
}
//ClientData cd = default(ClientData);
foreach (ClientData cd in ht.Values)
{
if (cd.structSocket.Connected)
{
cd.structSocket.Close();
}
if (cd.structThread.IsAlive)
{
cd.structThread.Abort();
}
}
if (tcpThd.IsAlive)
{
tcpThd.Abort();
}
this.Close();
}
}
}
这是 Client 类的代码...
This is the code for Client class...
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
//using System.Windows.Documents;
using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Imaging;
//using System.Windows.Navigation;
//using System.Windows.Shapes;
using System.Windows.Threading;
using System.Data.Common;
namespace DtposClient
{
/// <summary>
/// Interaction logic for TCPClient.xaml
/// </summary>
public partial class TCPClient : Window
{
public Thread tcpThd;
public byte[] readBuffer;
public byte[] writeBuffer;
public Stream stream;
public Socket socket;
public TcpClient tcpclnt;
public int password;
//===============================\\
public OleDbConnection connection = new OleDbConnection();
DataSet DtposMenuDS = new DataSet();
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter dtadapter = new OleDbDataAdapter();
public OleDbDataReader dataReader;
private ClientLogin loginForm = new ClientLogin();
public TCPClient()
{
InitializeComponent();
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\AP_AE\\Desktop\\DTPOS_ClientServer\\DataBase\\DtposMenu.accdb;";
//connection = new OleDbConnection(connectionString);
try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("Error Masseage = " + ex.Message);
}
if (connection.State != ConnectionState.Open)
{
MessageBox.Show("Database Connection Failed to Open");
//Application.Exit();
this.Close();
}
}
#region " Client, Start Server - (Client User is Connecting To Server) "
public void startServer(string ipAddress, int portNumber, int password)
{
try
{
connection.Open();
dtadapter.SelectCommand.CommandText = "SELECT * FROM Users WHERE Password = ''" + password + "'';";
//string commandString = "SELECT Password FROM [Users]";
//commandString += "WHERE(Password=@Param1)";
//OleDbDataAdapter dtadapter = new OleDbDataAdapter();
//DataTable myDataTable = new DataTable();
//OleDbCommand comm = new OleDbCommand();
dataReader = dtadapter.SelectCommand.ExecuteReader();
//comm.Connection = connection;
//comm.CommandType = CommandType.Text;
//comm.CommandText = commandString;
//comm.Parameters.Add("@Param1", OleDbType.Integer, 4).Value = txtPassword.Text;
//dtadapter.SelectCommand = comm;
//dtadapter.Fill(myDataTable);
dataReader.Read();
this.password = password;
tcpclnt = new TcpClient();
tcpclnt.Connect(ipAddress.Trim(), portNumber);
txtLoginWindow.AppendText("Connecting to server... " + "\n" + "======================================== " + "\n");
stream = tcpclnt.GetStream();
Thread.Sleep(4000);
txtLoginWindow.AppendText((" Hello " + dataReader["Name"].ToString() + ", " + " You have logged in as " + "''" + dataReader["Access Level"].ToString() + "''" + " Welcome to DTPOS System"));
tcpThd = new Thread(ReadSocket);
//tcpThd.Name = loginName
tcpThd.Start();
dataReader.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.StackTrace);
MessageBox.Show(ex.ToString(), "Unable to open database!");
}
connection.Close();
}
#endregion
#region " Client Read Socket "
public void ReadSocket()
{
while (true)
{
try
{
readBuffer = new Byte[101];
stream.Read(readBuffer, 0, 100);
// If the text box exceeds the maximum lenght, then get
// remove the top part of the text
if (txtLoginWindow.Text.Length > txtLoginWindow.MaxLength)
{
txtLoginWindow.Select(0, 300);
txtLoginWindow.SelectedText = "";
}
txtLoginWindow.AppendText((System.Text.Encoding.ASCII.GetString(readBuffer)));
}
catch (Exception)
{
break; // TODO: might not be correct. Was : Exit While
}
}
}
#endregion
#region " User Client Write To Server "
public void writeToServer(string strn)
{
System.Text.ASCIIEncoding encord = new System.Text.ASCIIEncoding();
writeBuffer = encord.GetBytes(strn);
if ((stream != null))
{
stream.Write(writeBuffer, 0, writeBuffer.Length);
}
}
#endregion
private void menuItemStart_Click(object sender, RoutedEventArgs e)
{
loginForm = new ClientLogin();
//loginForm.ShowDialog();
loginForm.infoChecker(this);
}
private void menuItemExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnLogout_Click(object sender, EventArgs e)
{
txtLoginWindow.AppendText(("Logging out from the server!!!"));
Thread.Sleep(3000);
//dataReader = new System.Data.OleDb.OleDbDataReader();
txtLoginWindow.AppendText(("User: " + dataReader["Name"].ToString() + " as " + dataReader["Access Level"].ToString() + " Has Logged Out... "));
this.btnLogout.IsEnabled = false;
//writeToServer((loginName & " has logged out... "));
if ((tcpThd != null) & tcpThd.IsAlive)
{
tcpThd.Abort();
}
if ((stream != null))
{
stream.Close();
}
if ((tcpclnt != null))
{
tcpclnt.Close();
}
}
}
}
这是客户登录类的代码....
This is the code for Client Login class....
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
//using System.Windows.Documents;
using System.Windows.Input;
//using System.Windows.Media;
//using System.Windows.Media.Imaging;
//using System.Windows.Navigation;
//using System.Windows.Shapes;
using System.Windows.Threading;
using System.Data.Common;
namespace DtposClient
{
/// <summary>
/// Interaction logic for ClientLogin.xaml
/// </summary>
public partial class ClientLogin : Window
{
TCPClient tcpclient;// = new TCPClient();
//==================================\\
DataSet DtposMenuDS = new DataSet();
public OleDbConnection connection = new OleDbConnection();
//public TextBox txtIPaddress = new System.Windows.Controls.TextBox();
//public TextBox txtPortNumber = new System.Windows.Controls.TextBox();
public ClientLogin()
{
InitializeComponent();
connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\AP_AE\\Desktop\\DTPOS_ClientServer\\DataBase\\DtposMenu.accdb;";
//connection = new OleDbConnection(connectionString);
/*try
{
connection.Open();
}
catch (Exception ex)
{
MessageBox.Show("DataBase Access Error");
MessageBox.Show("Error Masseage = " + ex.Message);
}
if (connection.State != ConnectionState.Open)
{
MessageBox.Show("Database Connection Failed to Open");
//Application.Exit();
this.Close();
}*/
}
public void infoChecker(TCPClient formOne)
{
this.tcpclient = formOne;
this.ShowDialog();
}
private void btnLogin_Click(object sender, RoutedEventArgs e)
{
try
{
connection.Open();
if (txtPassword.Text.Length == 0)
{
OleDbCommand command = new OleDbCommand();
OleDbDataAdapter dtadapter = new OleDbDataAdapter();
OleDbDataReader dataReader;
dtadapter.SelectCommand.CommandText = "SELECT * FROM [Users] WHERE Password = ''" + txtPassword.Text + "''";
dataReader = dtadapter.SelectCommand.ExecuteReader();
dataReader.Read();
MessageBox.Show(" You have loged as: - " + dataReader["Access Level"].ToString() + " Welcome " + dataReader["Name"].ToString() + " to DTPOS System ", "Login Successful", MessageBoxButton.OK, MessageBoxImage.Information);
UserLoginModule.UserAccessLevel = dataReader["Access Level"].ToString();
UserLoginModule.UserName = dataReader["Name"].ToString();
//ToDo: Error processing original source shown below
//--^--- Unexpected pre-processor directive
this.tcpclient.startServer(txtIpAddress.Text.ToString().Trim(), Convert.ToInt32(txtPortNumber.Text.ToString().Trim()), Convert.ToInt32(txtPassword.Text.ToString().Trim()));
// Always call Close when done reading.
dataReader.Close();
connection.Close();
this.Close();
}
else if (txtPassword.Text.Length < 4)
{
MessageBox.Show("You must enter data in order to proceed further. Please try again...", "Error: Non Data Entry", MessageBoxButton.OK, MessageBoxImage.Information);
txtPassword.Focus();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
MessageBox.Show(ex.ToString(), "Unable to open database!");
}
// Display error if unable to open database
}
private void btnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void btnReset_Click(object sender, RoutedEventArgs e)
{
txtPassword.Clear();
txtPassword.Focus();
}
}
}
这是 UserClien t属性类的代码...
This is the code for UserClient property class...
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DtposClient
{
public class UserClient
{
// User Client Global variables
// ====================================
public string UserName;
public string UserAccessLevel;
public int UserPassword;
public string fullName
{
get { return UserName; }
set { UserName = value; }
}
public string accLevel
{
get { return UserAccessLevel; }
set { UserAccessLevel = value; }
}
public int userPass
{
get { return UserPassword; }
set { UserPassword = value; }
}
public override bool Equals(object obj)
{
UserClient temp = obj as UserClient;
if (temp != null)
{
return (userPass == temp.userPass);
}
return false;
}
public UserClient(string fullNam, string aLevel, int pass)
{
fullName = fullNam;
accLevel = aLevel;
userPass = pass;
}
}
}
最后这是一个静态的 UserLoginModule 类...
And finally this is a static UserLoginModule class...
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
namespace DtposClient
{
static class UserLoginModule
{
public static ArrayList UserClientList = new ArrayList();
public static System.Collections.Hashtable ordersMap = new Hashtable();
// Global variables
public static string UserName;
public static string UserAccessLevel;
public static int UserPassword = 0;
public static UserClient CurrUserClient = null;
}
}
在此先感谢
亲切的问候
roni
thanks in advance
kind regards
roni
推荐答案
搜索 ^ ]提供了大量可供选择的选项.
通读此 [
Searching Google[^] provides a serious number of options to choose from.
Read through this[^] to get a firmer understanding of what you are asking about.
Regards
Espen Harlinn
这篇关于WPF客户端服务器登录应用程序,C#源代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!