C#中C/S登录界面 代码
时间: 2023-06-20 08:09:42 浏览: 142
C#登录界面代码
以下是一个简单的 C# C/S 登录界面代码,你可以参考一下:
客户端:
```csharp
using System;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace Client
{
public partial class LoginForm : Form
{
private TcpClient client;
private NetworkStream stream;
public LoginForm()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
client = new TcpClient();
client.Connect("127.0.0.1", 8888); // 连接服务器
stream = client.GetStream();
string username = txtUsername.Text.Trim();
string password = txtPassword.Text.Trim();
string loginInfo = "login " + username + " " + password;
byte[] buffer = Encoding.UTF8.GetBytes(loginInfo);
stream.Write(buffer, 0, buffer.Length);
buffer = new byte[1024];
int len = stream.Read(buffer, 0, buffer.Length);
string result = Encoding.UTF8.GetString(buffer, 0, len);
if (result == "success")
{
MessageBox.Show("登录成功");
}
else
{
MessageBox.Show("用户名或密码错误");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
stream?.Close();
client?.Close();
}
}
}
}
```
服务器端:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server
{
class Program
{
static void Main(string[] args)
{
TcpListener listener = new TcpListener(IPAddress.Any, 8888);
listener.Start();
Console.WriteLine("服务器已启动");
while (true)
{
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("客户端已连接");
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int len = stream.Read(buffer, 0, buffer.Length);
string loginInfo = Encoding.UTF8.GetString(buffer, 0, len);
string[] info = loginInfo.Split(' ');
string username = info[1];
string password = info[2];
if (username == "admin" && password == "123456")
{
buffer = Encoding.UTF8.GetBytes("success");
stream.Write(buffer, 0, buffer.Length);
}
else
{
buffer = Encoding.UTF8.GetBytes("fail");
stream.Write(buffer, 0, buffer.Length);
}
stream.Close();
client.Close();
}
}
}
}
```
注:为了简化代码,此示例中没有进行任何的安全验证,请勿在实际项目中使用。
阅读全文