应用介绍
分为三个模块:登录、注册以及通讯界面(服务器、客户端),这里程序运行基本是没有问题的,后续还会更新,大家有需要就关注一下,有问题的可以在评论区留言
登录界面
用户名、密码输入,与数据库对比,可选择进入注册及通讯界面
注册界面
输入个人信息,数据库建表,录入数据,完成后返回登录界面进行登录操作。
通讯界面
通讯界面由两部分组成:服务器端与客户端,现仍存在一个问题:在本机测试两个界面通讯是没有问题的,但两个不同机器就不行了,这个问题希望有大牛能够指出,谢谢
效果图及源代码
登录界面
这里注册会跳转到注册页面。登录进入通讯页面,取消按钮还没有写事件。说一下,这里连接有Mysql数据库,右击项目找到NuGet管理,添加MySql.Data包。
效果
程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using MySql.Data.MySqlClient;
using 注册;
using 客户端;
using Client = 客户端.Client;
namespace 注册登录界面
{
public partial class Login : Form
{
Register register=new Register();
客户端.Client client=new 客户端.Client();
public Login()
{
InitializeComponent();
}
private bool Mask()
{
string connectStr = "server=localhost;port=3306;user=root;password=123456;database=networkcommunication";
MySqlConnection conn = new MySqlConnection(connectStr);
conn.Open();
Console.WriteLine("数据库连接成功!");
string select_UserName = $"select Name from customer where UserName='{txtEdit_UserName.Text}' and Password='{txtEdit_Password.Text}'";
MySqlCommand cmd = new MySqlCommand(select_UserName, conn);
MySqlDataReader reader = cmd.ExecuteReader();
if (reader.Read())//如果用户名和密码正确则能查询到一条语句,即读取下一行返回true
{
XtraMessageBox.Show("登陆成功!");
return true;
}
else
{
XtraMessageBox.Show("用户名或密码不正确!");
return false;
}
}
private void sbt_Login_Click(object sender, EventArgs e)
{
if (Mask())
{
this.Hide();
if (client.ShowDialog()==DialogResult.OK)
{
this.Close();
}
}
}
private void sbt_Register_Click(object sender, EventArgs e)
{
this.Hide();
if (register.ShowDialog()==DialogResult.OK)
{
register.Close();
this.Show();
txtEdit_UserName.Text = null;
txtEdit_Password.Text = null;
}
}
}
}
注册界面
注册界面也是连库操作,跟上面登录界面导入数据库包操作一样,另外还需要添加一个EnumsNET,用于枚举获取输入的报错信息
效果
程序
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using MySql.Data.MySqlClient;
using EnumsNET;
using AttributeCollection = EnumsNET.AttributeCollection;
namespace 注册
{
public partial class Register : Form
{
private MySqlConnection conn;
private Customer customer;
//Register register=new Register();
public Register()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
string connectStr = "server=localhost;port=3306;user=root;password=123456;database=networkcommunication";
conn = new MySqlConnection(connectStr);
conn.Open();
if (KeyValueNull())return;
GetValue();
CreatTable();
InsertInto();
XtraMessageBox.Show("注册成功!");
this.DialogResult=DialogResult.OK;
}
private void GetValue()
{
customer = new Customer();
customer.Name = txtEdit_Name.Text;
customer.Sex = txtEdit_Sex.Text;
customer.Common = Convert.ToInt32(txtEdit_IdNumber.Text.Substring(6, 4));
customer.Age = DateTime.Now.Year - customer.Common+1;
customer.Birth = txtEdit_IdNumber.Text.Substring(6, 8);
customer.IdNumber = Convert.ToInt64(txtEdit_IdNumber.Text);
customer.NativePlace = txtEdit_NativePlace.Text;
customer.UserName = txtEdit_UserName.Text;
customer.Password = txtEdit_Password.Text;
}
private void InsertInto()
{
string msg =
$"insert into Customer(Name,Sex,Age,Birth,IdNumber,NativePlace,UserName,Password)" +
$"values('{customer.Name}','{customer.Sex}',{ customer.Age},{ customer.Birth}," +
$"{ customer.IdNumber},'{customer.NativePlace}','{customer.UserName}','{customer.Password}')";
try
{
MySqlCommand info = new MySqlCommand(msg, conn);
info.ExecuteNonQuery();
}
catch (Exception)
{
}
finally
{
conn.Close();
}
}
private void CreatTable()
{
try
{
MySqlCommand creatTable =
new MySqlCommand(
"create table Customer(Id int(5),Name char(10),Sex char(1),Age int(3) " +
",Birth datetime, IdNumber char(18), NativePlace char(10)," +
"UserName char(10), Password char(10))",
conn);
creatTable.ExecuteNonQuery();
}
catch (Exception)
{
}
}
private bool KeyValueNull()
{
if (CheckMsg(txtEdit_Name.Text, EnumValueNull.Name))return true;
if (CheckMsg(txtEdit_IdNumber.Text, EnumValueNull.IdNumber)) return true;
if (CheckMsg(txtEdit_UserName.Text, EnumValueNull.UserName)) return true;
if (CheckMsg(txtEdit_Password.Text, EnumValueNull.Password)) return true;
if (!txtEdit_Password.Text.Equals(txtEdit_PsdConfirmation.Text))
{
XtraMessageBox.Show("两次密码输入有误,请重新输入!");
txtEdit_Password.Text = null;
txtEdit_PsdConfirmation.Text = null;
return true;
}
return false;
}
private bool CheckMsg(string str,EnumValueNull file)
{
AttributeCollection attribute = file.GetAttributes();
DescriptionAttribute description = (DescriptionAttribute) attribute[0];
if (string.IsNullOrEmpty(str))
{
XtraMessageBox.Show(description.Description, "警告");
return true;
}
return false;
}
private enum EnumValueNull
{
[Description("姓名不能为空!")]
Name= 0,
[Description("身份证号不能为空!")]
IdNumber=1,
[Description("用户名不能为空!")]
UserName = 2,
[Description("密码不能为空!")]
Password = 3
}
private class Customer
{
public string Name { get; set; }
public string Sex { get; set; }
public int Age { get; set; }
public string Birth { get; set; }
public long IdNumber { get; set; }
public string NativePlace { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public int Common { get; set; }
}
}
}
通讯界面
效果
IP地址和端口号都是可以更改的
这里服务器的IP是自动获取(不可修改),端口号是可以修改的
这里操作需要注意的是,先打开服务器进行本地监听,然后再开启客户端进行连接,下拉框会加载连接到服务器的客户端,需要给谁发送消息就选择相应ed客户端,这里服务器的信息显示还有一点小问题,以后再改进程序再更新吧
程序
客户端
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace 客户端
{
public partial class Client : Form
{
Socket socket_send;
public Client()
{
InitializeComponent();
}
private void sbt_Connet_Click(object sender, EventArgs e)
{
try
{
socket_send = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Parse(tEt_Ip.Text);
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(tEt_ProtNumber.Text));
socket_send.Connect(point);
ShowMessage(0, "连接成功!");
Thread th_recive = new Thread(Recive);
th_recive.IsBackground = true;
th_recive.Start();
}
catch (Exception)
{
}
}
private void ShowMessage(int p,string str)
{
if (p==0)
{
memoEdit1.Text = $"{memoEdit1.Text}{socket_send.RemoteEndPoint}:{str}\r\n";
}
else if(p==1)
{
memoEdit2.Text= $"{memoEdit2.Text}To:{socket_send.RemoteEndPoint}\r\n{str}\r\n";
}
else
{
memoEdit2.Text = $"{memoEdit2.Text}{socket_send.RemoteEndPoint}\r\n{str}\r\n";
}
}
private void sbt_Send_Click(object sender, EventArgs e)
{
try
{
string str = textEdit1.Text;
byte[] buffer = Encoding.UTF8.GetBytes(str);
socket_send.Send(buffer);
ShowMessage(1, str);
textEdit1.Text = null;
}
catch (Exception){}
}
private void Recive()
{
try
{
while (true)
{
byte[] bytes = new byte[1024 * 1024];
int count = socket_send.Receive(bytes);
if (count == 0) break;
string str = Encoding.UTF8.GetString(bytes, 0, count);
ShowMessage(2, str);
}
}
catch (Exception){}
}
private void Client_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private void Client_FormClosing(object sender, FormClosingEventArgs e)
{
this.DialogResult=DialogResult.OK;
}
}
}
服务器
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.Utils.Extensions;
using static System.Net.Dns;
namespace 服务器
{
public partial class Server : Form
{
private Socket socket_Watch;
private Socket socket_send;
private Thread thread_Recive;
private DataTable ClientIpAdresses;
public Server()
{
InitializeComponent();
}
private void sbt_Start_Click(object sender, EventArgs e)
{
try
{
//在服务器端创建一个负责监听IP地址跟端口号的的Socket
socket_Watch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = IPAddress.Any;
//创建端口号对象
IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(tEt_PortNumber.Text));
//绑定监听端口
socket_Watch.Bind(point);
Information(0, "监听成功!");
socket_Watch.Listen(10);
Thread thread_Lisend = new Thread(Lisend);
thread_Lisend.IsBackground = true;
thread_Lisend.Start();
}
catch (Exception)
{
}
}
private void Information(int p,string infor)
{
if (p==0)
{
mEt_Information.Text = mEt_Information.Text + $"{infor}\r\n";
}
else if(p==1)
{
memoEdit1.Text = $"{memoEdit1.Text}To:{socket_send.RemoteEndPoint}\r\n{infor}\r\n";
}
else
{
memoEdit1.Text = $"{memoEdit1.Text}{socket_send.RemoteEndPoint}\r\n{infor}\r\n";
}
}
private void Lisend()
{
try
{
while (true)
{
socket_send = socket_Watch.Accept();
Information(0,$"{socket_send.RemoteEndPoint} :连接成功!");
//将连接上的客户端IP存入集合ClientAddresses
ClientIpAdresses.Rows.Add(socket_send,socket_send.RemoteEndPoint.ToString());
//lEt_ClientIp.EditValue = socket_send.RemoteEndPoint.ToString();
lEt_ClientIp.Properties.DataSource = ClientIpAdresses;
thread_Recive = new Thread(Recive);
thread_Recive.IsBackground = true;
thread_Recive.Start();
}
}
catch (Exception){ }
}
/// <summary>
/// 接收数据
/// </summary>
private void Recive()
{
try
{
while (true)
{
byte[] buffer = new byte[1024 * 1024];
int count = socket_send.Receive(buffer);
if (count == 0) break;
string str = Encoding.UTF8.GetString(buffer, 0, count);
Information(2,str);
}
}
catch (Exception){ }
}
private void Server_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
string hostName = GetHostName();
IPHostEntry ip = GetHostByName(hostName);
var firstOrDefault = ip.AddressList.FirstOrDefault();
if (firstOrDefault != null) tEt_Ip.Text = firstOrDefault.ToString();
ClientIpAdresses=new DataTable();
ClientIpAdresses.Columns.Add("Socket",typeof(Socket));
ClientIpAdresses.Columns.Add("客户端",typeof(string));
lEt_ClientIp.Properties.DataSource = ClientIpAdresses;
//text显示的值
lEt_ClientIp.Properties.DisplayMember = "客户端";
//下拉框显示
lEt_ClientIp.Properties.ValueMember = "客户端";
}
private void sbt_Send_Click(object sender, EventArgs e)
{
string str = textEdit1.Text;
byte[] bytes = Encoding.UTF8.GetBytes(str);
Socket send= ClientIpAdresses.Rows[lEt_ClientIp.ItemIndex][0] as Socket;
send.Send(bytes);
Information(1,str);
textEdit1.Text = null;
}
}
}