在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例C#语言基础 → C# Socket测试工具的开发亲测TCP UDP

C# Socket测试工具的开发亲测TCP UDP

C#语言基础

下载此实例
  • 开发语言:C#
  • 实例大小:10.52M
  • 下载次数:187
  • 浏览次数:1513
  • 发布时间:2018-04-12
  • 实例类别:C#语言基础
  • 发 布 人:zhu921230
  • 文件格式:.rar
  • 所需积分:10
 相关标签: Socket C# 工具 测试TCP UDP

实例介绍

【实例简介】

【实例截图】

from clipboard

【核心代码】




using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using SocketTool.Core;
using System.Threading;
using System.Diagnostics;

namespace SocketTool
{
    public partial class ServerForm : Form, ISocketInfo
    {
        public ServerForm()
        {
            InitializeComponent();
            SocketInfo = new SocketInfo();

        }

        //private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(ServerForm));  
        private IServer commServer = new CommTcpServer();

        private Thread refreshThread;

        private Boolean continueRefresh = true;

        private List<IConnection> conns = new List<IConnection>();

        public SocketInfo SocketInfo { get; set; }

        private void btnSend_Click(object sender, EventArgs e)
        {
        }

        private void btnListen_Click(object sender, EventArgs e)
        {

            if (rbUdp.Checked)
                commServer = new CommUdpServer();
            int port = int.Parse(this.txtPort.Text);

            commServer.Init(null, port);
            commServer.OnDataReceived = new ReceivedHandler(ListenMessage);
            commServer.OnSocketError = new SocketErrorHandler(ListenErrorMessage);

            //refreshThread = new Thread(new ThreadStart(RefreshConnection));
            if(refreshConnectionWorker.IsBusy == false)
               refreshConnectionWorker.RunWorkerAsync();
            try
            {
                commServer.Listen();
                btnListen.Enabled = false;
                btnStopListen.Enabled = true;
                ListenMessage(0, "", "启动监听成功,端口:" port);
            }
            catch (Exception ex)
            {
                MessageBox.Show("监听失败,端口可能被占用");
            }
        }

        public void ListenErrorMessage(object o, SocketEventArgs e)
        {
            string errorMsg = "[" e.ErrorCode "]" SocketUtil.DescrError(e.ErrorCode);

            ListenMessage(o, "Socket错误", errorMsg);

        }
        private void ListenMessage(object ID, string type, string msg)
        {
            if (PacketView.InvokeRequired)
            {
                try
                {
                    MsgHandler d = new MsgHandler(ListenMessage);
                    this.Invoke(d, new object[] { ID,type, msg });
                }
                catch (System.Exception ex)
                {
                    //logger.Error(ex.Message);
                    //logger.Error(ex.StackTrace);
                }
            }
            else
            {
                if (PacketView.Items.Count > 200)
                    PacketView.Items.Clear();


                ListViewItem item = PacketView.Items.Insert(0, "" PacketView.Items.Count);

                item.SubItems.Add("" ID);
                item.SubItems.Add("");
                //int length = e.Data.Length;
                string strDate = DateTime.Now.ToString("HH:mm:ss");
                item.SubItems.Add(strDate);
                item.SubItems.Add(msg);
                //item.SubItems.Add("" length);
            }
        }

        public void ListenMessage(object o, ReceivedEventArgs e)
        {
            if (PacketView.InvokeRequired)
            {
                
                    ReceivedHandler d = new ReceivedHandler(ListenMessage);
                    this.Invoke(d, new object[] { o, e});
            }
            else
            {
                byte[] data = e.Data;
                int length = data.Length;
                Boolean isEcho = this.cbAutoSend.Checked;
                string connId = "" o;
                if (isEcho)
                {
                    commServer.Send(connId, data, data.Length);
                }

                
                if (PacketView.Items.Count > 200)
                    PacketView.Items.Clear();

                ListViewItem item = PacketView.Items.Insert(0, "" PacketView.Items.Count);
                item.SubItems.Add("" connId);
                item.SubItems.Add("" e.RemoteHost.ToString());

                string msg = ParseUtil.ParseString(data, length);
                if (rbHex.Checked)
                {
                    msg = ParseUtil.ToHexString(data, length);
                }

                string strDate = DateTime.Now.ToString("HH:mm:ss");
                item.SubItems.Add(strDate);

                item.SubItems.Add(msg);
                item.SubItems.Add("" length);
                if (cbLog.Checked)
                {
                    //logger.Info(e.RemoteHost.ToString() " " msg);
                }
                //item.SubItems.Add("" msg.MsgContentDesc);
            }
        }

        private void btnStopListen_Click(object sender, EventArgs e)
        {
            commServer.Close();

            btnListen.Enabled = true;
            btnStopListen.Enabled = false;
        }

        private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            SocketInfo.ServerIp = this.txtIP.Text;
            try
            {
            SocketInfo.Port = int.Parse(this.txtPort.Text);
            }
            catch (System.Exception ex)
            {
            
            }
            SocketInfo.Protocol = rbTcp.Checked ? "Tcp" : "Udp";
            SocketInfo.Format = rbAscII.Checked ? "AscII" : "Hex";
            SocketInfo.Type = "Server";
            SocketInfo.Data = this.rtbData.Text;
            SocketInfo.IsAuto = cbAutoSend.Checked;
            refreshConnectionWorker.CancelAsync();
            commServer.Close();
        }

        private void btnClearLog_Click(object sender, EventArgs e)
        {
            this.PacketView.Items.Clear();
        }

        private void refreshConnectionWorker_DoWork(object sender, DoWorkEventArgs e)
        {
             int m = 0;
             while (continueRefresh)
             {
                 conns = commServer.GetConnectionList();
                 refreshConnectionWorker.ReportProgress(m);

                 Thread.Sleep(1000);
             }
        }

        private void refreshConnectionWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            try
            {

                connectionView.Items.Clear();
                foreach (IConnection ic in conns)
                {

                    ListViewItem item = connectionView.Items.Insert(0, "" connectionView.Items.Count);
                    item.Tag = ic.ID;
                    item.SubItems.Add("" ic.ID);
                    //int length = e.Data.Length;
                    string strDate = DateTime.Now.ToString("dd HH:mm:ss");
                    item.SubItems.Add(ic.CreateDate.ToString("dd HH:mm:ss"));
                    item.SubItems.Add(ic.ClientIP.ToString());
                    item.SubItems.Add(ic.OnlineDate.ToString("dd HH:mm:ss"));

                }
            }
            catch (System.Exception ex)
            {
                //logger.Error(ex.Message);
                //logger.Error(ex.StackTrace);
            }
        }

        private string selectedConnectionID;
        private void connectionView_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in connectionView.SelectedItems)
            {
                selectedConnectionID = "" item.Tag;

                txtConn.Text = item.SubItems[3].Text;
            }
            
        }

        private void PacketView_SelectedIndexChanged(object sender, EventArgs e)
        {
            foreach (ListViewItem item in PacketView.SelectedItems)
            {
                selectedConnectionID = "" item.Tag;
                rtbData.Text = item.SubItems[4].Text;
            }
        }

        private void ServerForm_Load(object sender, EventArgs e)
        {
            this.txtIP.Text = SocketInfo.ServerIp;
            rbTcp.Checked = SocketInfo.Protocol == "Tcp";
            rbUdp.Checked = SocketInfo.Protocol != "Tcp";
            rbAscII.Checked = SocketInfo.Format == "AscII";
            rbHex.Checked = SocketInfo.Format != "AscII";
            this.txtPort.Text = "" SocketInfo.Port;

            cbAutoSend.Checked = SocketInfo.IsAuto;
            this.rtbData.Text = SocketInfo.Data;
        }

        private void btnOpenLog_Click(object sender, EventArgs e)
        {
            Process.Start("notepad.exe", "server.log");
        }

    }
}


实例下载地址

C# Socket测试工具的开发亲测TCP UDP

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警