[转][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}\r\n字节形式:{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, \r });
                client.Send(result);
                client.Close();

                Invoke((MethodInvoker)delegate
                {
                    tsProgressBar1.Value = tsProgressBar1.Maximum;
                    if (txtResult.Lines.Length > 10000)
                        txtResult.Clear();
                    txtResult.Text = string.Format("{0}\r\n\r\n{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}\r\n\r\n{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}\r\n\r\n{1}", tmp, txtResult.Text);
            }
        }
        catch (Exception ex)
        {
            string tmp = string.Format("转换出错:{0}", ex.Message);
            log.Debug(tmp);
            txtResult.Text = string.Format("{0}\r\n\r\n{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);
    }
}

 

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

上一篇:C# 一般处理程序ashx用于验证码


下一篇:什么是API接口测试?用Restbird、Postman工具助力接口自动化测试