C# 服务端与客户端示例(Socket通信)

服务器、客户端示例.exe下载 

http://scimence.cn/soft/MessageServer/MessageServer_EXE.zip

 

服务器端源码:

 

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

    }
}

 

客户端源码:

 

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]");
        }
    }
}

 

安卓客户端Socket示例:https://blog.csdn.net/scimence/article/details/92832245

  • 14
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值