| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 519 人关注过本帖
标题:Socket通信问题,客户端连接服务端的时候,如何把用户名和密码也一起输过去 ...
只看楼主 加入收藏
tankin
Rank: 1
等 级:新手上路
帖 子:39
专家分:0
注 册:2011-4-12
结帖率:33.33%
收藏
已结贴  问题点数:20 回复次数:1 
Socket通信问题,客户端连接服务端的时候,如何把用户名和密码也一起输过去。
客户端连接服务端的时候,把用户名和密码也一起传过去做一个登录验证,验证一下现在连接的用户是否存在.....但是 socke.Connect(endPoint);这样只是可以和服务器做一个链接,根本传不了用户名和密码过去。望高手指点。
搜索更多相关主题的帖子: 密码 Socket 用户名 服务端 
2012-11-10 10:23
mmxo
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:13
帖 子:189
专家分:1090
注 册:2012-11-7
收藏
得分:20 
我的解决方案是这样的:连接后服务端发送一个命令“Give me your account”,客户端收到这个命令后将帐户信息传送给服务端,服务端进行验证,验证通过则发送命令“Okay”,不通过发送命令“NoSuchAccount”,客户端收到并判断是哪个命令,是“Okay”则显示“Ready.”并进入后续工作,收到“NoSuchAccount”表明没通过服务端拒绝了,这时显示“Verify failure!”并关闭连接。代码如下,包含了UI代码,实在不清楚就按我这个重建项目运行看一看应该就明白了。
程序代码:
//FormServer.cs
using System;
using System.Collections.Generic;
using using using using System.Text;
using System.Windows.Forms;

namespace ServerClient
{
    delegate void StringEventHandler    (string value);
    delegate void StringEventHandler2   (string value, string value2); 

    public partial class FormServer : Form
    {
        #region 只读全局字段

        private readonly byte[]                     _buffer;
        private readonly Dictionary<Socket, bool>   _clientAllowFlags;

        #endregion 

        #region 全局字段 

        private int    _currentClientId;
        private Socket _socketServer; 

        #endregion 

        #region 构造函数 

        public FormServer()
        {
            InitializeComponent();
            _buffer = new byte[512];
            _clientAllowFlags = new Dictionary<Socket, bool>();
            Closing += FormServer_Closing;
        } 

        #endregion 

        #region 控件事件

        private void ButStart_Click(object sender, EventArgs e)
        {
            ButStart.Enabled = false;
            _socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _socketServer.Bind(new IPEndPoint(IPAddress.Any, (int)NudPort.Value));
            _socketServer.Listen(10);
            _socketServer.BeginAccept(ClientAcceptedCallback, null);
          
            ShowInfo("Server is ready.");
            ButStop.Enabled = true;
        } 

        private void ButStop_Click(object sender, EventArgs e)
        {
            ButStop.Enabled = false;
            _socketServer.Close();
            ShowInfo("Server is stopped.");
            ButStart.Enabled = true;
        } 

        void FormServer_Closing(object sender, CancelEventArgs e)
        {
            if (_socketServer == null) return;
            _socketServer.Close();
        } 

        #endregion

        #region Socket事件 

        private void ClientAcceptedCallback(IAsyncResult ar)
        {
            try
            {
                var clientSocket = _socketServer.EndAccept(ar);
                _clientAllowFlags.Add(clientSocket, false);
                clientSocket.Send(Encoding.Unicode.GetBytes(string.Concat("Give me your account:", _currentClientId)));
                _currentClientId++;
                ShowInfo(string.Concat("Client[",_currentClientId, "] connected. Wait for account information..."));
                clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceivedCallback, clientSocket);
                _socketServer.BeginAccept(ClientAcceptedCallback, null);
            }
            catch { }
        } 

        private void ReceivedCallback(IAsyncResult ar)
        {
            var clientSocket = ar.AsyncState as Socket;
            if (clientSocket == null) return;
            try
            {
                var dataLength = clientSocket.EndReceive(ar);
                var data = Encoding.Unicode.GetString(_buffer, 0, dataLength);
                var elements = data.Split(':');
                var command = elements[0];
                switch (command)
                {
                    case "Account":
                        {
                            var accountElements = elements[1].Split(',');
                            var userName = accountElements[0];
                            var password = accountElements[1]; 

                            //用你自己的验证逻辑替换这段
                            _clientAllowFlags[clientSocket] = userName == "UserName" && password == "Password";
                            //用你自己的验证逻辑替换这段 

                            if (_clientAllowFlags[clientSocket])
                            {
                                clientSocket.Send(Encoding.Unicode.GetBytes("Okay"));
                                ShowInfo("Verified.");
                            }
                            else
                            {
                                clientSocket.Send(Encoding.Unicode.GetBytes("NoSuchAccount"));
                                _clientAllowFlags.Remove(clientSocket);
                                ShowInfo("No allow.");
                            }
                        }
                        break;

                    case "DC":
                        if (!_clientAllowFlags[clientSocket]) break;
                        ShowInfo(string.Concat("Client[", elements[1], "] disconnected."));
                        break; 

                    case "Info":
                        if (!_clientAllowFlags[clientSocket]) break;
                        ShowInfo(elements[1], elements[2]);
                        break;
                }
                clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceivedCallback, clientSocket);
            }
            catch { }
        } 

        #endregion 

        #region 私有方法

        private void ShowInfo(string info)
        {
            if (InvokeRequired)
                Invoke(new StringEventHandler(ShowInfo), new object[] {info});
            else
            {
                TbState.AppendText(DateTime.Now.ToLongTimeString());
                TbState.AppendText("");
                TbState.AppendText(info);
                TbState.AppendText("\r\n");
            }
        } 

        private void ShowInfo(string clientID, string info)
        {
            if (InvokeRequired)
                Invoke(new StringEventHandler2(ShowInfo), new object[] { clientID, info });
            else
            {
                TbState.AppendText(DateTime.Now.ToLongTimeString());
                TbState.AppendText("");
                TbState.AppendText(clientID);
                TbState.AppendText("");
                TbState.AppendText(info);
                TbState.AppendText("\r\n");
            }
        } 

        #endregion
    }
}
//FormClient.cs
using System;
using using System.Text;
using System.Windows.Forms; 

namespace ClientServer
{
    internal delegate void IntegerEventHandler(int value);
    delegate void StringEventHandler(string value);

    public partial class FormClient : Form
    {
        #region 只读全局字段 

        private readonly byte[] _buffer; 

        #endregion 

        #region 全局字段 

        private Socket  _clientSocket;
        private int     _id; 

        #endregion 

        #region 构造函数 

        public FormClient()
        {
            InitializeComponent();
            _buffer = new byte[512];
        } 

        #endregion 

        #region 控件事件 

        private void ButConnect_Click(object sender, EventArgs e)
        {
            ButConnect.Enabled = false;
            _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _clientSocket.Connect("localhost", (int)NudPort.Value);
            _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceivedCallback, null);
            ShowInfo("Connected.");
            ButDisconnect.Enabled = true;
        } 

        private void ButDisconnect_Click(object sender, EventArgs e)
        {
            Disconnect();
        } 

        private void ButSendCommand_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(TbCommand.Text)) return;
            _clientSocket.Send(Encoding.Unicode.GetBytes(string.Concat("Info:", _id, ":", TbCommand.Text)));
        } 

        #endregion 

        #region Socket事件 

        private void ReceivedCallback(IAsyncResult ar)
        {
            try
            {
                var dataLength = _clientSocket.EndReceive(ar);
                var data = Encoding.Unicode.GetString(_buffer, 0, dataLength);
                var elements = data.Split(':');
                var command = elements[0];
                switch (command)
                {
                    case "Give me your account":
                        {
                            _id = int.Parse(elements[1]);
                            SetIDProcess();
                            //用需要验证的用户名和密码替换这句里面的UserName和Password
                            _clientSocket.Send(Encoding.Unicode.GetBytes(string.Concat("Account:", "UserName,", "Password")));
                        }
                        break; 

                    case "NoSuchAccount":
                        ShowInfo("Verify failure!");
                        Disconnect();
                        break; 

                    case "Okay":
                        ShowInfo("Ready.");
                        break; 

                    case "Info":
                        ShowInfo(elements[1]);
                        break;
                }
                _clientSocket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceivedCallback, null);
            }
            catch { }
        } 

        #endregion 

        #region 私有方法 

        private void Disconnect()
        {
            if (InvokeRequired)
                Invoke(new MethodInvoker(Disconnect));
            else
            {
                ButDisconnect.Enabled = false;
                _clientSocket.Send(Encoding.Unicode.GetBytes(string.Concat("DC:", _id)));
                _clientSocket.Close();
                ShowInfo("Disconnected");
                ButConnect.Enabled = true;
            }
        } 

        private void SetIDProcess()
        {
            if (InvokeRequired)
                Invoke(new MethodInvoker(SetIDProcess));
            else
            {
                Text = string.Concat("Client [", _id, "] by ");
                ShowInfo(string.Concat("My ID is ", _id));
            }
        } 

        private void ShowInfo(string info)
        {
            if (InvokeRequired)
                Invoke(new StringEventHandler(ShowInfo), new object[] { info });
            else
            {
                TbState.AppendText(DateTime.Now.ToLongTimeString());
                TbState.AppendText("");
                TbState.AppendText(info);
                TbState.AppendText("\r\n");
            }
        } 

        #endregion
    }
}
//FormServer.Designer.cs
namespace ServerClient
{
    partial class FormServer
    {
        private  components = null;
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null)) components.Dispose();
            base.Dispose(disposing);
        } 

        private void InitializeComponent()
        {
            this.ButStart = new System.Windows.Forms.Button();
            this.ButStop = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.TbState = new System.Windows.Forms.TextBox();
            this.NudPort = new System.Windows.Forms.NumericUpDown();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.groupBox1.SuspendLayout();
            (()(this.NudPort)).BeginInit();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout(); 

            this.ButStart.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top |
                                     System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
            this.ButStart.Location = new System.Drawing.Point(108, 25);
            this.ButStart.Name = "ButStart";
            this.ButStart.Size = new System.Drawing.Size(117, 23);
            this.ButStart.TabIndex = 0;
            this.ButStart.Text = "启动(&S)";
            this.ButStart.UseVisualStyleBackColor = true;
            this.ButStart.Click += new System.EventHandler(this.ButStart_Click);
            this.ButStop.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top |
                                    System.Windows.Forms.AnchorStyles.Right)));
            this.ButStop.Enabled = false;
            this.ButStop.Location = new System.Drawing.Point(231, 25);
            this.ButStop.Name = "ButStop";
            this.ButStop.Size = new System.Drawing.Size(94, 23);
            this.ButStop.TabIndex = 1;
            this.ButStop.Text = "停止(&T)";
            this.ButStop.UseVisualStyleBackColor = true;
            this.ButStop.Click += new System.EventHandler(this.ButStop_Click); 

            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles) ((((System.Windows.Forms.AnchorStyles.Top |
                                      System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) |
                                      System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox1.Controls.Add(this.TbState);
            this.groupBox1.Location = new System.Drawing.Point(12, 61);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(316, 102);
            this.groupBox1.TabIndex = 4;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "状态"; 

            this.TbState.Dock = System.Windows.Forms.DockStyle.Fill;
            this.TbState.Location = new System.Drawing.Point(3, 17);
            this.TbState.MaxLength = 3276700;
            this.TbState.Multiline = true;
            this.TbState.Name = "TbState";
            this.TbState.ReadOnly = true;
            this.TbState.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.TbState.Size = new System.Drawing.Size(310, 82);
            this.TbState.TabIndex = 3; 

            this.NudPort.Location = new System.Drawing.Point(7, 16);
            this.NudPort.Maximum = new decimal(new int[] { 65535, 0, 0, 0 });
            this.NudPort.Minimum = new decimal(new int[] { 100, 0, 0, 0 });
            this.NudPort.Name = "NudPort";
            this.NudPort.Size = new System.Drawing.Size(67, 21);
            this.NudPort.TabIndex = 6;
            this.NudPort.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.NudPort.Value = new decimal(new int[] { 3636, 0, 0, 0 });

            this.groupBox2.Controls.Add(this.NudPort);
            this.groupBox2.Location = new System.Drawing.Point(12, 12);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(81, 43);
            this.groupBox2.TabIndex = 7;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "端口号"; 

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(340, 175);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.ButStop);
            this.Controls.Add(this.ButStart);
            this.Name = "FormServer";
            this.ShowIcon = false;
            this.Text = "Server by ";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            (()(this.NudPort)).EndInit();
            this.groupBox2.ResumeLayout(false);
            this.ResumeLayout(false);
        }
        private System.Windows.Forms.Button ButStart;
        private System.Windows.Forms.Button ButStop;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.TextBox TbState;
        private System.Windows.Forms.NumericUpDown NudPort;
        private System.Windows.Forms.GroupBox groupBox2;
    }
} 

//FormClient.Designer.cs
namespace ClientServer
{
    partial class FormClient
    {
        private  components = null;

        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null)) components.Dispose();
            base.Dispose(disposing);
        } 

        private void InitializeComponent()
        {
            this.ButConnect = new System.Windows.Forms.Button();
            this.ButDisconnect = new System.Windows.Forms.Button();
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.TbState = new System.Windows.Forms.TextBox();
            this.TbCommand = new System.Windows.Forms.TextBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.ButSendCommand = new System.Windows.Forms.Button();
            this.groupBox3 = new System.Windows.Forms.GroupBox();
            this.NudPort = new System.Windows.Forms.NumericUpDown();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.groupBox3.SuspendLayout();
            (()(this.NudPort)).BeginInit();
            this.SuspendLayout(); 

            this.ButConnect.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top |
                                       System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
            this.ButConnect.Location = new System.Drawing.Point(109, 25);
            this.ButConnect.Name = "ButConnect";
            this.ButConnect.Size = new System.Drawing.Size(121, 23);
            this.ButConnect.TabIndex = 1;
            this.ButConnect.Text = "连接服务器(&C)";
            this.ButConnect.UseVisualStyleBackColor = true;
            this.ButConnect.Click += new System.EventHandler(this.ButConnect_Click); 

            this.ButDisconnect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top |
                                          System.Windows.Forms.AnchorStyles.Right)));
            this.ButDisconnect.Enabled = false;
            this.ButDisconnect.Location = new System.Drawing.Point(236, 25);
            this.ButDisconnect.Name = "ButDisconnect";
            this.ButDisconnect.Size = new System.Drawing.Size(92, 23);
            this.ButDisconnect.TabIndex = 2;
            this.ButDisconnect.Text = "断开连接(&D)";
            this.ButDisconnect.UseVisualStyleBackColor = true;
            this.ButDisconnect.Click += new System.EventHandler(this.ButDisconnect_Click);

            this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top |
                                      System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) |
                                      System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox1.Controls.Add(this.TbState);
            this.groupBox1.Location = new System.Drawing.Point(12, 122);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(316, 125);
            this.groupBox1.TabIndex = 3;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "状态"; 

            this.TbState.Dock = System.Windows.Forms.DockStyle.Fill;
            this.TbState.Location = new System.Drawing.Point(3, 17);
            this.TbState.MaxLength = 3276700;
            this.TbState.Multiline = true;
            this.TbState.Name = "TbState";
            this.TbState.ReadOnly = true;
            this.TbState.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.TbState.Size = new System.Drawing.Size(310, 105);
            this.TbState.TabIndex = 3; 

            this.TbCommand.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top |
                                      System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
            this.TbCommand.Location = new System.Drawing.Point(6, 20);
            this.TbCommand.Name = "TbCommand";
            this.TbCommand.Size = new System.Drawing.Size(228, 21);
            this.TbCommand.TabIndex = 5; 

            this.groupBox2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top |
                                      System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right)));
            this.groupBox2.Controls.Add(this.ButSendCommand);
            this.groupBox2.Controls.Add(this.TbCommand);
            this.groupBox2.Location = new System.Drawing.Point(12, 61);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(316, 55);
            this.groupBox2.TabIndex = 6;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "命令"; 

            this.ButSendCommand.Location = new System.Drawing.Point(240, 18);
            this.ButSendCommand.Name = "ButSendCommand";
            this.ButSendCommand.Size = new System.Drawing.Size(70, 23);
            this.ButSendCommand.TabIndex = 6;
            this.ButSendCommand.Text = "发送(&S)";
            this.ButSendCommand.UseVisualStyleBackColor = true;
            this.ButSendCommand.Click += new System.EventHandler(this.ButSendCommand_Click); 

            this.groupBox3.Controls.Add(this.NudPort);
            this.groupBox3.Location = new System.Drawing.Point(12, 12);
            this.groupBox3.Name = "groupBox3";
            this.groupBox3.Size = new System.Drawing.Size(91, 43);
            this.groupBox3.TabIndex = 8;
            this.groupBox3.TabStop = false;
            this.groupBox3.Text = "服务器端口号"; 

            this.NudPort.Location = new System.Drawing.Point(7, 16);
            this.NudPort.Maximum = new decimal(new int[] { 65535, 0, 0, 0});
            this.NudPort.Minimum = new decimal(new int[] { 100, 0, 0, 0});
            this.NudPort.Name = "NudPort";
            this.NudPort.Size = new System.Drawing.Size(78, 21);
            this.NudPort.TabIndex = 6;
            this.NudPort.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            this.NudPort.Value = new decimal(new int[] {3636, 0, 0, 0}); 

            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(340, 259);
            this.Controls.Add(this.groupBox3);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Controls.Add(this.ButDisconnect);
            this.Controls.Add(this.ButConnect);
            this.Name = "FormClient";
            this.ShowIcon = false;
            this.Text = "Client by ";
            this.groupBox1.ResumeLayout(false);
            this.groupBox1.PerformLayout();
            this.groupBox2.ResumeLayout(false);
            this.groupBox2.PerformLayout();
            this.groupBox3.ResumeLayout(false);
            (()(this.NudPort)).EndInit();
            this.ResumeLayout(false);
        } 

        private System.Windows.Forms.Button ButConnect;
        private System.Windows.Forms.Button ButDisconnect;
        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.TextBox TbCommand;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Button ButSendCommand;
        private System.Windows.Forms.TextBox TbState;
        private System.Windows.Forms.GroupBox groupBox3;
        private System.Windows.Forms.NumericUpDown NudPort;
    }
}





[ 本帖最后由 mmxo 于 2012-11-10 17:34 编辑 ]

为提高中华编程水平而奋斗
2012-11-10 17:28
快速回复:Socket通信问题,客户端连接服务端的时候,如何把用户名和密码也一起输 ...
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.054677 second(s), 10 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved