最近因为课程需要,写了一个简单的BS的结构的,有客户端服务器的简易程序,但是整体效果不是很理想,不知道为什么在传送数据的过程中会出错,而且偶尔有异常报出。

 

整个软件的思想是:需要一个服务器,为每一个用户维护一个文件目录,用户可以上传和下载文件。再次基础上,我实现了显示在线用户的功能,显示在线用户的功能完成很好,几乎不会出错,用户上线和下线服务器都会通知其他的用户。

 

先给出客户端登录的简易代码:

 
using System; using System.Collections.Generic; using System.ComponentModel;
using System.Data; using System.Drawing; using System.Linq; using System.Text;
using System.Windows.Forms; using System.Net; using System.Net.Sockets;
namespace Client { public partial class Login : Form { IPAddress serverIP =
null; private int server_port; TcpClient tcpClient = null; public Login() {
InitializeComponent(); this.textBox_ip.Text = "10.108.13.27";
this.textBox_port.Text = "8888"; } private void button2_Click(object sender,
EventArgs e) { this.Close(); } private void button1_Click(object sender,
EventArgs e) { // 检查用户出入的参数是否合法 string name = textBox1.Text.TrimEnd('\0') ;
string password = textBox2.Text.TrimEnd('\0'); if (name == "" || password ==
""||textBox_ip.Text==""||textBox_port.Text=="") { MessageBox.Show("错误的输入参数",
"shit"); return; } else { // 用户输入的用户名和密码符合程序要求规范,和服务器进行通信,判断用户是否有权限登录系统
serverIP = IPAddress.Parse(textBox_ip.Text); server_port =
int.Parse(textBox_port.Text); tcpClient = new TcpClient(); // 建立和服务器的连接
tcpClient.Connect(serverIP,server_port); if (tcpClient == null) {
MessageBox.Show("无法连接到服务器,请重试!", "错误", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation); } else { // 建立用于访问网络的基本数据流 NetworkStream netStream
= tcpClient.GetStream(); byte[] name_byte = Encoding.Unicode.GetBytes(name);
byte[] password_byte = Encoding.Unicode.GetBytes(password); // 分别给服务器发送用户名和密码
netStream.Write(name_byte,0,name_byte.Length); netStream.Flush(); byte[] test =
new byte[2]; netStream.Read(test, 0, test.Length); netStream.Flush();
netStream.Write(password_byte,0,password_byte.Length); netStream.Flush(); //
接受服务器返回的登录反馈 byte[] echo_from_server = new byte[100];
netStream.Read(echo_from_server,0,echo_from_server.Length); string echo_string
= Encoding.Unicode.GetString(echo_from_server).TrimEnd('\0'); //
用equals,不用==判断字符串 if (echo_string.Equals("failed")) {
MessageBox.Show("用户名密码错误,请重新填写", "提示", MessageBoxButtons.OK,
MessageBoxIcon.Information); this.textBox1.Text = ""; this.textBox2.Text = "";
this.tcpClient = null; return; } else if(echo_string.Equals("success")) { //
允许用户登录 MessageBox.Show("登录成功"); MainForm mainForm = new MainForm(name,
netStream); mainForm.Owner = this; this.Hide(); mainForm.Show(); } } } }
private void Login_Load(object sender, EventArgs e) { //
//this.textBox2.PasswordChar = '*'; } } }

 

技术
今日推荐
PPT
阅读数 115
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:ixiaoyang8@qq.com
QQ群:766591547
关注微信