• [转][C#]Socket 手写服务端


        private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name);
        private Socket server;
        private Thread thread;
        private bool First = true;
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            timer1.Start();
        }
    
        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Stop();
    
            tssTime.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss dddd");
            if (First)
            {
                First = false;
    
                var ips = Dns.GetHostByName(Dns.GetHostName());
                foreach (var item in ips.AddressList)
                {
                    tssIP.DropDownItems.Add(item.ToString());
                }
                if (tssIP.DropDownItems.Count > 0)
                    tssIP.Text = tssIP.DropDownItems[0].Text;
                tssStart.PerformClick();
            }
            timer1.Start();
        }
    
        private void tssStart_Click(object sender, EventArgs e)
        {
            if (tssStart.BackColor == Color.Green)
            {
                tssStart.BackColor = SystemColors.Control;
                tssInfo.Text = "停止监听";
            }
            else
            {
                tssStart.BackColor = Color.Green;
                tssInfo.Text = "开始监听";
    
                SocketStart();
            }
        }
    
        private void SocketStart()
        {
            if (server != null)
            {
                try
                {
                    thread.Abort();
                    server.Close();
                }
                catch { }
            }
    
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint local = new IPEndPoint(IPAddress.Parse(tssIP.Text), ConvertHelper.ToInt(txtPort.Text));
            server.Bind(local);
            server.Listen(200);
    
            thread = new Thread(() =>
            {
                while (true)
                {
                    //Thread.Sleep(500);
                    Invoke((MethodInvoker)delegate
                    {
                        tsProgressBar1.Value = tsProgressBar1.Minimum;
                    });
                    Socket client = server.Accept();
                    byte[] buffer = new byte[4096];
                    int bytes = client.Receive(buffer, buffer.Length, SocketFlags.None);
    
                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < bytes; i++)
                    {
                        sb.AppendFormat("{0} ", buffer[i].ToString("x2"));
                    }
    
                    string str = string.Format("{0} 接收到 {1} 发送到 {2} 的消息:{3}
    字节形式:{4} ",
                        DateTime.Now.ToString("HH:mm"),
                        client.RemoteEndPoint,
                        client.LocalEndPoint,
                        Encoding.ASCII.GetString(buffer, 0, bytes),
                        sb.ToString());
                    log.Debug(str);
    
                    var result = Encoding.ASCII.GetBytes(new char[] { 'O', 'K', '
    ' });
                    client.Send(result);
                    client.Close();
    
                    Invoke((MethodInvoker)delegate
                    {
                        tsProgressBar1.Value = tsProgressBar1.Maximum;
                        if (txtResult.Lines.Length > 10000)
                            txtResult.Clear();
                        txtResult.Text = string.Format("{0}
    
    {1}", str, txtResult.Text);
                    });
                }
            });
            thread.IsBackground = true;
            thread.Start();
        }
    
        private void tssIP_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            tssIP.Text = e.ClickedItem.Text;
            ResetStart();
        }
    
        private void ResetStart()
        {
            tssStart.PerformClick();
            if (tssStart.BackColor != Color.Green)
                tssStart.PerformClick();
        }
    
        private void txtText_Enter(object sender, EventArgs e)
        {
            txtText.BackColor = Color.White;
            txtByte.BackColor = Color.WhiteSmoke;
        }
    
        private void txtByte_Enter(object sender, EventArgs e)
        {
            txtText.BackColor = Color.WhiteSmoke;
            txtByte.BackColor = Color.White;
        }
    
        private void btnTest_Click(object sender, EventArgs e)
        {
            try
            {
                if (txtText.BackColor == Color.White)
                {
                    // 转 十六进制
                    bool success = true;
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in txtText.Text)
                    {
                        int c = (int)item;
                        if (c > 0xff)
                            success = false;
                        sb.AppendFormat("{0} ", ((byte)item).ToString("x2"));
                    }
                    txtByte.Text = sb.ToString();
    
                    string tmp = string.Format("转换:{0} -> {1}", txtText.Text, txtByte.Text);
                    log.Debug(tmp);
                    txtResult.Text = string.Format("{0}
    
    {1}", tmp, txtResult.Text);
                    if (!success)
                    {
                        ShowErr("不能转换汉字!");
                        log.Debug("转换出错:不能转换汉字!");
                    }
                }
                else
                {
                    string[] strs = txtByte.Text.Trim().Split(' ');
                    byte[] bs = new byte[strs.Length];
                    for (int i = 0; i < strs.Length; i++)
                    {
                        bs[i] = Convert.ToByte(strs[i], 16);
                    }
                    txtText.Text = Encoding.ASCII.GetString(bs);
                    string tmp = string.Format("转换:{0} -> {1}", txtByte.Text, txtText.Text);
                    log.Debug(tmp);
                    txtResult.Text = string.Format("{0}
    
    {1}", tmp, txtResult.Text);
                }
            }
            catch (Exception ex)
            {
                string tmp = string.Format("转换出错:{0}", ex.Message);
                log.Debug(tmp);
                txtResult.Text = string.Format("{0}
    
    {1}", tmp, txtResult.Text);
                if (ex.InnerException != null)
                    log.DebugFormat("转换出错:{0}", ex.InnerException.Message);
                ShowErr(ex.Message);
            }
        }
    
        private void ShowErr(string text)
        {
            MessageBox.Show(this, text, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }
    }
  • 相关阅读:
    vue+webpack搭建项目基础架构
    vue入门学习篇——父子组件通信
    vue入门学习篇——数据双向绑定原理及简单实现
    vue入门学习篇——挂载点、实例、模版之间的关系
    毫秒转成天、小时、分钟、秒
    可执行jar包的MANIFEST.MF
    fsck系统修复
    HDFS, YARN, HBase, Hive, ZooKeeper端口说明
    解压 tar zxvf 文件名.tar.gz 压缩 tar zcvf 文件名.tar.gz 目标名
    Linux学习笔记之RedHat Enterprise Linux 6.4 使用 Centos 6 的yum源问题
  • 原文地址:https://www.cnblogs.com/z5337/p/13283449.html
Copyright © 2020-2023  润新知