1. 程式人生 > >C# 服務端與客戶端示例(Socket通訊)

C# 服務端與客戶端示例(Socket通訊)


伺服器端原始碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MessageServer
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main(String[] args)
        {
            if (args.Length > 1)    // 通過命令列引數啟動服務,如: call "%~dp0MessageServer.exe" 127.0.0.1 37280
            {
                new Server(null, args[0], args[1]).start();
            }
            else
            {   // 通過windows窗體啟動服務
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new MessageServer());
            }
        }
    }
}
namespace MessageServer
{
    using System;
    using System.Collections.Generic;
    using System.Net;
    using System.Net.Sockets;
    using System.Runtime.CompilerServices;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Threading;

    public class Server
    {
        public string ipString = "127.0.0.1";   // 伺服器端ip
        public int port = 37280;                // 伺服器埠
        
        public Socket socket;
        public Print print;                     // 執行時的資訊輸出方法

        public Dictionary<string, Socket> clients = new Dictionary<string, Socket>();   // 儲存連線到伺服器的客戶端資訊
        public bool started = false;            // 標識當前是否啟動了服務

        public Server(Print print = null, string ipString = null, int port = -1)
        {
            this.print = print;
            if (ipString != null) this.ipString = ipString;
            if (port >= 0)this.port = port;
        }

        public Server(Print print = null, string ipString = null, string port = "-1")
        {
            this.print = print;
            if (ipString != null) this.ipString = ipString;

            int port_int = Int32.Parse(port);
            if (port_int >= 0) this.port = port_int;
        }

        /// <summary>
        /// Print用於輸出Server的輸出資訊
        /// </summary>
        public delegate void Print(string info);

        /// <summary>
        /// 啟動服務
        /// </summary>
        public void start()
        {
            try
            {
                IPAddress address = IPAddress.Parse(ipString);
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.Bind(new IPEndPoint(address, port));   
                socket.Listen(10000);

                if (print != null)
                {
                    try { print("啟動服務【" + socket.LocalEndPoint.ToString() + "】成功"); }
                    catch { print = null; }
                }
                started = true;

                new Thread(listenClientConnect).Start(socket);  // 在新的執行緒中監聽客戶端連線
            }
            catch (Exception exception)
            {
                if (print != null)
                {
                    print("啟動服務失敗 " + exception.ToString());
                }
                started = false;
            }
        }

        /// <summary>
        /// 監聽客戶端的連線
        /// </summary>
        private void listenClientConnect(object obj)
        {
            Socket socket = (Socket) obj;
            while (true)
            {
                Socket clientScoket = socket.Accept();
                if (print != null)
                {
                    print("客戶端" + clientScoket.RemoteEndPoint.ToString() + "已連線");
                }
                new Thread(receiveData).Start(clientScoket);   // 在新的執行緒中接收客戶端資訊

                Thread.Sleep(1000);                            // 延時1秒後,接收連線請求
                if (!started) return;
            }
        }

        /// <summary>
        /// 傳送資訊
        /// </summary>
        public void Send(string info, string id)
        {
            if (clients.ContainsKey(id))
            {
                Socket socket = clients[id];

                try 
                { 
                    Send(socket, info); 
                }
                catch(Exception ex)
                {
                    clients.Remove(id);
                    if (print != null) print("客戶端已斷開,【" + id + "】");
                }
            }
        }

        /// <summary>
        /// 通過socket傳送資料data
        /// </summary>
        private void Send(Socket socket, string data)
        {
            if (socket != null && data != null && !data.Equals(""))
            {
                byte[] bytes = Encoding.UTF8.GetBytes(data);   // 將data轉化為byte陣列
                socket.Send(bytes);                            // 
            }
        }

        private string clientIp = "";
        /// <summary>
        /// 輸出Server的輸出資訊到客戶端
        /// </summary>
        public void PrintOnClient(string info)
        {
            Send(info, clientIp);
        }

        /// <summary>
        /// 接收通過socket傳送過來的資料
        /// </summary>
        private void receiveData(object obj)
        {
            Socket socket = (Socket) obj;

            string clientIp = socket.RemoteEndPoint.ToString();                 // 獲取客戶端標識 ip和埠
            if (!clients.ContainsKey(clientIp)) clients.Add(clientIp, socket);  // 將連線的客戶端socket新增到clients中儲存
            else clients[clientIp] = socket;

            while (true)
            {
                try
                {
                    string str = Receive(socket);
                    if (!str.Equals(""))
                    {
                        if (str.Equals("[.Echo]"))
                        {
                            this.clientIp = clientIp;
                            print = new Print(PrintOnClient);     // 在客戶端顯示伺服器輸出資訊
                        }
                        if (print != null) print("【" + clientIp + "】" + str);

                        if (str.Equals("[.Shutdown]")) Environment.Exit(0); // 伺服器退出
                        else if (str.StartsWith("[.RunCmd]")) runCMD(str);  // 執行cmd命令
                    }
                }
                catch (Exception exception)
                {
                    if (print != null) print("連線已自動斷開,【" + clientIp + "】" + exception.Message);

                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();

                    if (clients.ContainsKey(clientIp)) clients.Remove(clientIp);
                    return;
                }

                if (!started) return;
                Thread.Sleep(200);      // 延時0.2秒後再接收客戶端傳送的訊息
            }
        }

        /// <summary>
        /// 執行cmd命令
        /// </summary>
        private void runCMD(string cmd)
        {
            new Thread(runCMD_0).Start(cmd);
        }

        /// <summary>
        /// 執行cmd命令
        /// </summary>
        private void runCMD_0(object obj)
        {
            string cmd = (string)obj;
            string START = "[.RunCmd]";
            if (cmd.StartsWith(START))
            {
                cmd = cmd.Substring(START.Length);  // 獲取cmd資訊
                Cmd.Run(cmd, print);                // 執行cmd,輸出執行結果到print
            }
        }

        /// <summary>
        /// 從socket接收資料
        /// </summary>
        private string Receive(Socket socket)
        {
            string data = "";

            byte[] bytes = null;
            int len = socket.Available;
            if (len > 0)
            {
                bytes = new byte[len];
                int receiveNumber = socket.Receive(bytes);
                data = Encoding.UTF8.GetString(bytes, 0, receiveNumber);
            }

            return data;
        }

        /// <summary>
        /// 停止服務
        /// </summary>
        public void stop()
        {
            started = false;
        }
    }
}
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MessageServer
{
    /// <summary>
    /// 執行CMD命令,或以程序的形式開啟應用程式(d:\*.exe)
    /// </summary>
    public class Cmd
    {
        /// <summary>
        /// 以後臺程序的形式執行應用程式(d:\*.exe)
        /// </summary>
        public static Process newProcess(String exe)
        {
            Process P = new Process();
            P.StartInfo.CreateNoWindow = true;
            P.StartInfo.FileName = exe;
            P.StartInfo.UseShellExecute = false;
            P.StartInfo.RedirectStandardError = true;
            P.StartInfo.RedirectStandardInput = true;
            P.StartInfo.RedirectStandardOutput = true;
            //P.StartInfo.WorkingDirectory = @"C:\windows\system32";
            P.Start();
            return P;
        }

        /// <summary>
        /// 執行CMD命令
        /// </summary>
        public static string Run(string cmd)
        {
            Process P = newProcess("cmd.exe");
            P.StandardInput.WriteLine(cmd);
            P.StandardInput.WriteLine("exit");
            string outStr = P.StandardOutput.ReadToEnd();
            P.Close();
            return outStr;
        }

        /// <summary>
        /// 定義委託介面處理函式,用於實時處理cmd輸出資訊
        /// </summary>
        public delegate void Callback(String line);

        ///// <summary>
        ///// 此函式用於實時顯示cmd輸出資訊, Callback示例
        ///// </summary>
        //private void Callback1(String line)
        //{
        //    textBox1.AppendText(line);
        //    textBox1.AppendText(Environment.NewLine);
        //    textBox1.ScrollToCaret();

        //    richTextBox1.SelectionColor = Color.Green;
        //    richTextBox1.AppendText(line);
        //    richTextBox1.AppendText(Environment.NewLine);
        //    richTextBox1.ScrollToCaret();
        //}


        /// <summary>
        /// 執行CMD語句,實時獲取cmd輸出結果,輸出到call函式中
        /// </summary>
        /// <param name="cmd">要執行的CMD命令</param>
        public static string Run(string cmd, Server.Print call)
        {
            String CMD_FILE = "cmd.exe"; // 執行cmd命令

            Process P = newProcess(CMD_FILE);
            P.StandardInput.WriteLine(cmd);
            P.StandardInput.WriteLine("exit");

            string outStr = "";
            string line = "";
            string baseDir = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd('\\');

            try
            {
                for (int i = 0; i < 3; i++) P.StandardOutput.ReadLine();

                while ((line = P.StandardOutput.ReadLine()) != null || ((line = P.StandardError.ReadToEnd()) != null && !line.Trim().Equals("")))
                {
                    // cmd執行輸出資訊
                    if (!line.EndsWith(">exit") && !line.Equals(""))
                    {
                        if (line.StartsWith(baseDir + ">")) line = line.Replace(baseDir + ">", "cmd>\r\n"); // 識別的cmd命令列資訊
                        line = ((line.Contains("[Fatal Error]") || line.Contains("ERROR:") || line.Contains("Exception")) ? "【E】 " : "") + line;
                        if (call != null) call(line);
                        outStr += line + "\r\n";
                    }
                }
            }
            catch (Exception ex)
            {
                if (call != null) call(ex.Message);
                //MessageBox.Show(ex.Message);
            }

            P.WaitForExit();
            P.Close();

            return outStr;
        }


        /// <summary>
        /// 以程序的形式開啟應用程式(d:\*.exe),並執行命令
        /// </summary>
        public static void RunProgram(string programName, string cmd)
        {
            Process P = newProcess(programName);
            if (cmd.Length != 0)
            {
                P.StandardInput.WriteLine(cmd);
            }
            P.Close();
        }


        /// <summary>
        /// 正常啟動window應用程式(d:\*.exe)
        /// </summary>
        public static void Open(String exe)
        {
            System.Diagnostics.Process.Start(exe);
        }

        /// <summary>
        /// 正常啟動window應用程式(d:\*.exe),並傳遞初始命令引數
        /// </summary>
        public static void Open(String exe, String args)
        {
            System.Diagnostics.Process.Start(exe, args);
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MessageServer
{
    public partial class MessageServer : Form
    {
        Server server;

        public MessageServer()
        {
            InitializeComponent();
        }

        // 啟動服務
        private void button_start_Click(object sender, EventArgs e)
        {
            if (server == null) server = new Server(SeverPrint, textBox_Ip.Text, textBox_Port.Text);
            if (!server.started) server.start();
        }

        // 伺服器端輸出資訊
        private void SeverPrint(string info)
        {
            if (textBox_showing.IsDisposed) server.print = null;
            else
            {
                if (textBox_showing.InvokeRequired)
                {
                    Server.Print F = new Server.Print(SeverPrint);
                    this.Invoke(F, new object[] { info });
                }
                else
                {
                    if (info != null)
                    {
                        textBox_showing.SelectionColor = Color.Green;
                        textBox_showing.AppendText(info);
                        textBox_showing.AppendText(Environment.NewLine);
                        textBox_showing.ScrollToCaret();
                    }
                }
            }
        }

        // 傳送資訊到客戶端
        private void button_send_Click(object sender, EventArgs e)
        {
            if (server != null) server.Send(textBox_send.Text, comboBox_clients.Text);
        }

        private void MessageServer_FormClosed(object sender, FormClosedEventArgs e)
        {
            //if (server != null) server.stop();
        }

        // 選擇客戶端時,更新客戶端列表資訊
        private void comboBox_clients_DropDown(object sender, EventArgs e)
        {
            if (server != null)
            {
                List<string> clientList = server.clients.Keys.ToList<string>();
                comboBox_clients.DataSource = clientList;
            }
        }

    }
}
namespace MessageServer
{
    partial class MessageServer
    {
        /// <summary>
        /// 必需的設計器變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設計器生成的程式碼

        /// <summary>
        /// 設計器支援所需的方法 - 不要
        /// 使用程式碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.textBox_Port = new System.Windows.Forms.TextBox();
            this.textBox_Ip = new System.Windows.Forms.TextBox();
            this.button_start = new System.Windows.Forms.Button();
            this.textBox_send = new System.Windows.Forms.TextBox();
            this.button_send = new System.Windows.Forms.Button();
            this.comboBox_clients = new System.Windows.Forms.ComboBox();
            this.label_clientIp = new System.Windows.Forms.Label();
            this.textBox_showing = new System.Windows.Forms.RichTextBox();
            this.SuspendLayout();
            // 
            // textBox_Port
            // 
            this.textBox_Port.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_Port.Location = new System.Drawing.Point(243, 3);
            this.textBox_Port.Name = "textBox_Port";
            this.textBox_Port.Size = new System.Drawing.Size(49, 21);
            this.textBox_Port.TabIndex = 19;
            this.textBox_Port.Text = "37280";
            // 
            // textBox_Ip
            // 
            this.textBox_Ip.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_Ip.Location = new System.Drawing.Point(84, 3);
            this.textBox_Ip.Name = "textBox_Ip";
            this.textBox_Ip.Size = new System.Drawing.Size(153, 21);
            this.textBox_Ip.TabIndex = 18;
            this.textBox_Ip.Text = "127.0.0.1";
            // 
            // button_start
            // 
            this.button_start.Location = new System.Drawing.Point(3, 3);
            this.button_start.Name = "button_start";
            this.button_start.Size = new System.Drawing.Size(75, 23);
            this.button_start.TabIndex = 17;
            this.button_start.Text = "啟動服務";
            this.button_start.UseVisualStyleBackColor = true;
            this.button_start.Click += new System.EventHandler(this.button_start_Click);
            // 
            // textBox_send
            // 
            this.textBox_send.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_send.Location = new System.Drawing.Point(3, 259);
            this.textBox_send.Multiline = true;
            this.textBox_send.Name = "textBox_send";
            this.textBox_send.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox_send.Size = new System.Drawing.Size(289, 37);
            this.textBox_send.TabIndex = 16;
            // 
            // button_send
            // 
            this.button_send.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.button_send.Location = new System.Drawing.Point(217, 298);
            this.button_send.Name = "button_send";
            this.button_send.Size = new System.Drawing.Size(75, 23);
            this.button_send.TabIndex = 15;
            this.button_send.Text = "傳送資訊";
            this.button_send.UseVisualStyleBackColor = true;
            this.button_send.Click += new System.EventHandler(this.button_send_Click);
            // 
            // comboBox_clients
            // 
            this.comboBox_clients.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.comboBox_clients.FormattingEnabled = true;
            this.comboBox_clients.Location = new System.Drawing.Point(73, 298);
            this.comboBox_clients.Name = "comboBox_clients";
            this.comboBox_clients.Size = new System.Drawing.Size(138, 20);
            this.comboBox_clients.TabIndex = 20;
            this.comboBox_clients.DropDown += new System.EventHandler(this.comboBox_clients_DropDown);
            // 
            // label_clientIp
            // 
            this.label_clientIp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.label_clientIp.AutoSize = true;
            this.label_clientIp.Location = new System.Drawing.Point(1, 301);
            this.label_clientIp.Name = "label_clientIp";
            this.label_clientIp.Size = new System.Drawing.Size(65, 12);
            this.label_clientIp.TabIndex = 21;
            this.label_clientIp.Text = "選擇客戶端";
            // 
            // textBox_showing
            // 
            this.textBox_showing.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.textBox_showing.Location = new System.Drawing.Point(3, 27);
            this.textBox_showing.Name = "textBox_showing";
            this.textBox_showing.Size = new System.Drawing.Size(289, 229);
            this.textBox_showing.TabIndex = 22;
            this.textBox_showing.Text = "";
            // 
            // MessageServer
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(295, 322);
            this.Controls.Add(this.textBox_showing);
            this.Controls.Add(this.label_clientIp);
            this.Controls.Add(this.comboBox_clients);
            this.Controls.Add(this.textBox_Port);
            this.Controls.Add(this.textBox_Ip);
            this.Controls.Add(this.button_start);
            this.Controls.Add(this.textBox_send);
            this.Controls.Add(this.button_send);
            this.Name = "MessageServer";
            this.ShowInTaskbar = false;
            this.Text = "伺服器";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MessageServer_FormClosed);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBox_Port;
        private System.Windows.Forms.TextBox textBox_Ip;
        private System.Windows.Forms.Button button_start;
        private System.Windows.Forms.TextBox textBox_send;
        private System.Windows.Forms.Button button_send;
        private System.Windows.Forms.ComboBox comboBox_clients;
        private System.Windows.Forms.Label label_clientIp;
        private System.Windows.Forms.RichTextBox textBox_showing;

    }
}

客戶端原始碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MessageClient
{
    static class Program
    {
        /// <summary>
        /// 應用程式的主入口點。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MessageClient());
        }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MessageClient
{
    class Client
    {
        public string ipString = "127.0.0.1";   // 伺服器端ip
        public int port = 37280;                // 伺服器埠
        public Socket socket;
        public Print print;                     // 執行時的資訊輸出方法
        public bool connected = false;          // 標識當前是否連線到伺服器
        public string localIpPort = "";         // 記錄本地ip埠資訊

        public Client(Print print = null, string ipString = null, int port = -1)
        {
            this.print = print;
            if (ipString != null) this.ipString = ipString;
            if (port >= 0) this.port = port;
        }

        public Client(Print print = null, string ipString = null, string port = "-1")
        {
            this.print = print;
            if (ipString != null) this.ipString = ipString;

            int port_int = Int32.Parse(port);
            if (port_int >= 0) this.port = port_int;
        }


        /// <summary>
        /// Print用於輸出Server的輸出資訊
        /// </summary>
        public delegate void Print(string info);

        /// <summary>
        /// 啟動客戶端,連線至伺服器
        /// </summary>
        public void start()
        {
            //設定伺服器IP地址  
            IPAddress ip = IPAddress.Parse(ipString);
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                socket.Connect(new IPEndPoint(ip, port));   // 連線伺服器
                if (print != null) print("連線伺服器【" + socket.RemoteEndPoint.ToString() + "】完成"); // 連線成功
                localIpPort = socket.LocalEndPoint.ToString();
                connected = true;

                Thread thread = new Thread(receiveData);
                thread.Start(socket);      // 在新的執行緒中接收伺服器資訊

            }
            catch (Exception ex)
            {
                if (print != null) print("連線伺服器失敗 " + ex.ToString()); // 連線失敗
                connected = false;
            }
        }

        /// <summary>
        /// 結束客戶端
        /// </summary>
        public void stop()
        {
            connected = false;
        }

        /// <summary>
        /// 傳送資訊
        /// </summary>
        public void Send(string info)
        {
            try
            {
                Send(socket, info);
            }
            catch (Exception ex)
            {
                if (print != null) print("伺服器端已斷開,【" + socket.RemoteEndPoint.ToString() + "】");
            }
        }

        /// <summary>
        /// 通過socket傳送資料data
        /// </summary>
        private void Send(Socket socket, string data)
        {
            if (socket != null && data != null && !data.Equals(""))
            {
                byte[] bytes = Encoding.UTF8.GetBytes(data);   // 將data轉化為byte陣列
                socket.Send(bytes);                            // 
            }
        }

        /// <summary>
        /// 接收通過socket傳送過來的資料
        /// </summary>
        private void receiveData(object socket)
        {
            Socket ortherSocket = (Socket)socket;

            while (true)
            {
                try
                {
                    String data = Receive(ortherSocket);       // 接收客戶端傳送的資訊
                    if (!data.Equals(""))
                    {
                        //if (print != null) print("伺服器" + ortherSocket.RemoteEndPoint.ToString() + "資訊:\r\n" + data);
                        if (print != null) print(data);
                        if (data.Equals("[.Shutdown]")) System.Environment.Exit(0);
                    }
                }
                catch (Exception ex)
                {
                    if (print != null) print("連線已自動斷開," + ex.Message);
                    ortherSocket.Shutdown(SocketShutdown.Both);
                    ortherSocket.Close();
                    connected = false;
                    break;
                }

                if (!connected) break;
                Thread.Sleep(200);      // 延時0.2後處理接收到的資訊
            }
        }

        /// <summary>
        /// 從socket接收資料
        /// </summary>
        private string Receive(Socket socket)
        {
            string data = "";

            byte[] bytes = null;
            int len = socket.Available;
            if (len > 0)
            {
                bytes = new byte[len];
                int receiveNumber = socket.Receive(bytes);
                data = Encoding.UTF8.GetString(bytes, 0, receiveNumber);
            }

            return 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;

namespace MessageClient
{
    public partial class MessageClient : Form
    {
        Client client;    // 客戶端例項

        public MessageClient()
        {
            InitializeComponent();
        }

        // 連線伺服器
        private void button_connect_Click(object sender, EventArgs e)
        {
            if (client == null) client = new Client(ClientPrint, textBox_Ip.Text, textBox_Port.Text);
            if (!client.connected) client.start();
            if (client != null) this.Text = "客戶端 " + client.localIpPort;
        }

        // 客戶端輸出資訊
        private void ClientPrint(string info)
        {
            if (textBox_showing.InvokeRequired)
            {
                Client.Print F = new Client.Print(ClientPrint);
                this.Invoke(F, new object[] { info });
            }
            else
            {
                if (info != null)
                {
                    textBox_showing.SelectionColor = Color.Green;
                    textBox_showing.AppendText(info);
                    textBox_showing.AppendText(Environment.NewLine);
                    textBox_showing.ScrollToCaret();
                }
            }
        }

        // 傳送資訊到伺服器
        private void button_send_Click(object sender, EventArgs e)
        {
            if (client != null && client.connected)
            {
                string info = textBox_send.Text;
                if (checkBox_isCmd.Checked && !info.StartsWith("[.RunCmd]"))    // 新增cmd串頭資訊
                    info = "[.RunCmd]" + info;

                client.Send(info);
            }
        }

        // 關閉介面停止服務執行
        private void MessageClient_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (client != null && client.connected)
                client.stop();
        }

        private void linkLabel_closeServer_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (client != null && client.connected)
                client.Send("[.Shutdown]");
        }

        private void linkLabel_Echo_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (client != null && client.connected)
                client.Send("[.Echo]");
        }
    }
}
namespace MessageClient
{
    partial class MessageClient
    {
        /// <summary>
        /// 必需的設計器變數。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的資源。
        /// </summary>
        /// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗體設計器生成的程式碼

        /// <summary>
        /// 設計器支援所需的方法 - 不要
        /// 使用程式碼編輯器修改此方法的內容。
        /// </summary>
        private void InitializeComponent()
        {
            this.button_connect = new System.Windows.Forms.Button();
            this.textBox_send = new System.Windows.Forms.TextBox();
            this.button_send = new System.Windows.Forms.Button();
            this.textBox_Ip = new System.Windows.Forms.TextBox();
            this.textBox_Port = new System.Windows.Forms.TextBox();
            this.linkLabel_closeServer = new System.Windows.Forms.LinkLabel();
            this.checkBox_isCmd = new System.Windows.Forms.CheckBox();
            this.textBox_showing = new System.Windows.Forms.RichTextBox();
            this.linkLabel_Echo = new System.Windows.Forms.LinkLabel();
            this.SuspendLayout();
            // 
            // button_connect
            // 
            this.button_connect.Location = new System.Drawing.Point(3, 7);
            this.button_connect.Name = "button_connect";
            this.button_connect.Size = new System.Drawing.Size(75, 23);
            this.button_connect.TabIndex = 11;
            this.button_connect.Text = "連線伺服器";
            this.button_connect.UseVisualStyleBackColor = true;
            this.button_connect.Click += new System.EventHandler(this.button_connect_Click);
            // 
            // textBox_send
            // 
            this.textBox_send.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_send.Location = new System.Drawing.Point(3, 263);
            this.textBox_send.Multiline = true;
            this.textBox_send.Name = "textBox_send";
            this.textBox_send.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox_send.Size = new System.Drawing.Size(289, 37);
            this.textBox_send.TabIndex = 10;
            // 
            // button_send
            // 
            this.button_send.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.button_send.Location = new System.Drawing.Point(217, 302);
            this.button_send.Name = "button_send";
            this.button_send.Size = new System.Drawing.Size(75, 23);
            this.button_send.TabIndex = 9;
            this.button_send.Text = "傳送資訊";
            this.button_send.UseVisualStyleBackColor = true;
            this.button_send.Click += new System.EventHandler(this.button_send_Click);
            // 
            // textBox_Ip
            // 
            this.textBox_Ip.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) 
            | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_Ip.Location = new System.Drawing.Point(84, 7);
            this.textBox_Ip.Name = "textBox_Ip";
            this.textBox_Ip.Size = new System.Drawing.Size(153, 21);
            this.textBox_Ip.TabIndex = 12;
            this.textBox_Ip.Text = "127.0.0.1";
            // 
            // textBox_Port
            // 
            this.textBox_Port.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.textBox_Port.Location = new System.Drawing.Point(243, 7);
            this.textBox_Port.Name = "textBox_Port";
            this.textBox_Port.Size = new System.Drawing.Size(49, 21);
            this.textBox_Port.TabIndex = 13;
            this.textBox_Port.Text = "37280";
            // 
            // linkLabel_closeServer
            // 
            this.linkLabel_closeServer.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.linkLabel_closeServer.AutoSize = true;
            this.linkLabel_closeServer.Location = new System.Drawing.Point(1, 306);
            this.linkLabel_closeServer.Name = "linkLabel_closeServer";
            this.linkLabel_closeServer.Size = new System.Drawing.Size(65, 12);
            this.linkLabel_closeServer.TabIndex = 14;
            this.linkLabel_closeServer.TabStop = true;
            this.linkLabel_closeServer.Text = "關閉伺服器";
            this.linkLabel_closeServer.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel_closeServer_LinkClicked);
            // 
            // checkBox_isCmd
            // 
            this.checkBox_isCmd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
            this.checkBox_isCmd.AutoSize = true;
            this.checkBox_isCmd.Location = new System.Drawing.Point(109, 306);
            this.checkBox_isCmd.Name = "checkBox_isCmd";
            this.checkBox_isCmd.Size = new System.Drawing.Size(102, 16);
            this.checkBox_isCmd.TabIndex = 15;
            this.checkBox_isCmd.Text = "以cmd格式傳送";
            this.checkBox_isCmd.UseVisualStyleBackColor = true;
            // 
            // textBox_showing
            // 
            this.textBox_showing.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.textBox_showing.Location = new System.Drawing.Point(4, 31);
            this.textBox_showing.Name = "textBox_showing";
            this.textBox_showing.Size = new System.Drawing.Size(287, 230);
            this.textBox_showing.TabIndex = 16;
            this.textBox_showing.Text = "";
            // 
            // linkLabel_Echo
            // 
            this.linkLabel_Echo.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
            this.linkLabel_Echo.AutoSize = true;
            this.linkLabel_Echo.Location = new System.Drawing.Point(2, 248);
            this.linkLabel_Echo.Name = "linkLabel_Echo";
            this.linkLabel_Echo.Size = new System.Drawing.Size(65, 12);
            this.linkLabel_Echo.TabIndex = 17;
            this.linkLabel_Echo.TabStop = true;
            this.linkLabel_Echo.Text = "伺服器輸出";
            this.linkLabel_Echo.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel_Echo_LinkClicked);
            // 
            // MessageClient
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(295, 327);
            this.Controls.Add(this.linkLabel_Echo);
            this.Controls.Add(this.textBox_showing);
            this.Controls.Add(this.checkBox_isCmd);
            this.Controls.Add(this.linkLabel_closeServer);
            this.Controls.Add(this.textBox_Port);
            this.Controls.Add(this.textBox_Ip);
            this.Controls.Add(this.button_connect);
            this.Controls.Add(this.textBox_send);
            this.Controls.Add(this.button_send);
            this.Name = "MessageClient";
            this.Text = "客戶端";
            this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MessageClient_FormClosed);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button_connect;
        private System.Windows.Forms.TextBox textBox_send;
        private System.Windows.Forms.Button button_send;
        private System.Windows.Forms.TextBox textBox_Ip;
        private System.Windows.Forms.TextBox textBox_Port;
        private System.Windows.Forms.LinkLabel linkLabel_closeServer;
        private System.Windows.Forms.CheckBox checkBox_isCmd;
        private System.Windows.Forms.RichTextBox textBox_showing;
        private System.Windows.Forms.LinkLabel linkLabel_Echo;
    }
}

開源地址

相關推薦

C# 服務客戶示例Socket通訊

伺服器端原始碼: using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms;

TCP連線斷開詳解socket通訊

一、TCP資料報結構以及三次握手 TCP(Transmission Control Protocol,傳輸控制協議)是一種面向連線的、可靠的、基於位元組流的通訊協議,資料在傳輸前要建立連線,傳輸完畢後還要斷開連線。 客戶端在收發資料前要使用 connect() 函式和伺服

C# Socket簡單例子服務客戶通信

項目 回車 pop ace log () client protocol comm 這個例子只是簡單實現了如何使用 Socket 類實現面向連接的通信。 註意:此例子的目的只是為了說明用套接字寫程序的大概思路,而不是實際項目中的使用程序。在這個例子中,實際上還有很多問題

Untiy中用C#實現TCP通訊Socket通訊服務客戶皆可

簡而言之,TCP通訊原理大家可以從各種網路文獻上找到,這裡不做贅述。 只提出C#實現TCP通訊的一般方法和常用程式碼工具供第一次接觸TCP通訊的玩家參考,老玩家繞道。。。 為了方便大家理解我的程式碼,會適當提及通訊遠離。 1、建立服務端,TCP連線的基本: using U

C#伺服器客戶通訊客戶

客戶端登陸介面 先定義三個視窗級變數(全域性變數) private TcpClient client;         private NetworkStream stream;         private

C#伺服器客戶通訊伺服器

Tcp協議+socket 1.伺服器端開始監聽 //通過winform視窗輸入的伺服器ip地址和埠號  myip = IPAddress.Parse(textBox1.Text);  myport = Int32.Parse(textBox2.Text);

grpc-服務客戶四種資料傳遞方式2

gpc服務端和客戶端的資料傳送有四種方式,客戶端啟動服務端的啟動程式碼在上篇文章已經描述,這裡將只列出關鍵實現的程式碼。 1.客戶端傳送一個物件,服務端返回一個物件 這種方式類似於傳統的Http請求資料的方式,在上篇文章有一個簡單的實現例子,在這裡不再描

ubuntu下安裝 gSOAP 用於C/C++開發web service服務客戶

首先下載gsoap,我下載的是gsoap-2.8.1.zip 用unzip gsoap-2.8.1.zip命令解壓縮,會解壓生成gsoap-2.8資料夾。 cd gsoap-2.8 在安裝之前需要先安裝一些編譯工具。 安裝編譯工具:   $sudo apt-get install buil

Unity使用C#實現簡單Scoket連線及服務客戶通訊

簡介:網路程式設計是個很有意思的事情,偶然翻出來很久之前剛開始看Socket的時候寫的一個例項,貼出來吧Unity中實現簡單的Socket連線,c#中提供了豐富的API,直接上程式碼。服務端程式碼: Thread connectThread;//當前服務端監聽子執行緒

C# socket 服務客戶通訊演示程式碼

string strMsg = sokMsg.RemoteEndPoint.ToString()+"說:"+"rn"+System.Text.Encoding.UTF8.GetString(arrMsg, 0, length); //// 我在這裡  Request.ServerVariables.Ge

C++ socket 實現服務客戶互相通訊

// Server.cpp : Defines the entry point for the console application. // #include "winsock2.h" #pragma comment(lib, "ws2_32.lib")

C#實現Thrift服務客戶

這一篇是將Android和C#實現Thrift服務端和客戶端中C#部分單獨拆分開來的,方便不需要Android的開發者使用。 編寫Thrift檔案 寫個簡單的,有輸入引數,無返回值,檔案命名為 HelloWorld.thrift service Hello

Mina學習1:mina實現簡單服務客戶

mina是一個基於javaNio網路通訊應用框架,使用mina可以輕鬆的搭建伺服器,接下來將使用mina搭建一個小型的服務端 原始碼–MinaServer.java package serv

Java中利用socket實現簡單的服務客戶通訊入門級

Java程式設計中,要想要使用網路通訊,就離不開Socket程式設計,在此對socket進行簡單的介紹。首先宣告,這是一個入門級的介紹,僅僅簡單的實現了客戶端向服務端傳送資料,服務端正常的接收資料,當接收到特定的資料時,服務端和客戶端都關閉,一個服務端對應一個客戶端,不涉及

Java中利用socket實現簡單的服務客戶通訊基礎級

在上一篇文章中,簡單的介紹了java中入門級的socket程式設計,簡單的實現了客戶端像伺服器端傳送資料,伺服器端將資料接收並顯示在控制檯,沒有涉及多執行緒。上一篇文章的連結:Java中利用socket實現簡單的服務端與客戶端的通訊(入門級) 這次,我們將上一節中的程式碼進

oracle服務客戶字符集不同導致中文亂碼解決方案

use 修改環境變量 描述 image nls_lang oracle服務 環境 分析 導致 1.問題描述 用pl/sql登錄時,會提示“數據庫字符集(ZHS16GBK)和客戶端字符集(2%)是不同的,字符集轉化可能會造成不可預期的後果”,具體問題是中文亂碼,如下圖 2.

TCP網絡程序實例——服務客戶交互

href tcpclient 端口號 信息 try 本機ip 發送數據 定義 .cn ◆ 服務器端 創建服務器端項目Server,在Main方法中創建TCP連接對象;然後監聽客戶端接入,並讀取接入的客戶端IP地址和傳入的消息;最後向接入的客戶端發送一條信息。代碼如下:

nagios 服務客戶監控安裝詳細配置,各配置文件詳解

this sql 引入 apache2 cpu load fine 宕機 pri require nagios 安裝與部署—————— 1、安裝前準備(1)創建nagios用戶和用戶組 [root@localhost ~]#groupadd nagios

NFS文件系統、服務客戶安裝、exportfs命令

NFS exportfs命令 NFS服務端安裝 NFS客戶端安裝 NFS介紹 NFS是Network File system的縮寫,也就是網絡文件系統;基於RPC協議進行傳輸; 服務端安裝 yum install -y nfs-utils rpcbind //安裝rpcbind包

html原理簡介、第一個網頁服務客戶

直接 ack 字符 time() true nec utf-8 RM 成了 #coding=utf-8 """ HTML: 20個標簽 一套瀏覽器認識的規則 學習規則。開發後臺程序:寫html文件 本地測試:找到文件直接雙擊打