我想用C#做一个基于TCP/IP,定时发送数据(每隔1s),实时接受数据,怎么做,谢谢

解决方案 »

  1.   

    UP,如果是TCP的协议的话,就用TCPListener和TCPClient
    如果是UDP的话,就用UDPClient
    如果你想自由的控制的话,就直接用Socket。
      

  2.   

    socket通信 客户端 服务端
      

  3.   

     private void TcpServer_Load(object sender, EventArgs e)
            {
                Form.CheckForIllegalCrossThreadCalls = false;            System.Timers.Timer t = new System.Timers.Timer(180000);//实例化Timer类,设置间隔时间为10000毫秒
                t.Elapsed += new System.Timers.ElapsedEventHandler(theout);//到达时间的时候执行事件
                t.AutoReset = true;//设置是执行一次(false)还是一直执行(true) 
                t.Enabled = true;//是否执行System.Timers.Timer.Elapsed事件
                try
                {
                    ThreadStart thsrt = new ThreadStart(Listen);
                    mythread = new Thread(thsrt);
                    mythread.Start();
                    State = false;
                    this.BtnStart.Text = "停止监听";
                    this.Messagetxt.Text = "服务已启动,正在侦听...";
                }
                catch (Exception ex)
                {
                    DAL.Log.Write(DateTime.Now + ex.ToString() + "\r\n\r\n");
                }
            }        private object threadlock = new object();
            /// <summary>
            /// 启动监听
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void BtnStart_Click(object sender, EventArgs e)
            {
                //锁定区域同时进行数据处理
                Monitor.Enter(threadlock);
                try
                {
                    //启动线程
                    ThreadStart thsrt = new ThreadStart(Listen);
                    //10个线程全部执行统一的方法
                    Thread[] threads = new Thread[10];                //mythread = new Thread(thsrt);
                    if (State)   //如果状态是true,表示可以开启
                    {
                        //循环10个线程
                        for (int i = 0; i < 10; i++)
                        {
                            threads[i] = new Thread(thsrt);
                            //设置线程为后台后台线程 ,也叫守护线程
                            threads[i].IsBackground = true;
                        }
                        //循环遍历所有的10个线程
                        foreach (Thread th in threads)
                        {
                            //开启线程
                            th.Start();
                        }
                        //mythread.Start();
                        //线程睡眠10毫秒
                        Thread.Sleep(10);
                        //将状态改为false
                        State = false;
                        this.BtnStart.Text = "停止监听";
                        this.Messagetxt.Text = "服务已启动,正在侦听...";
                    }
                    else
                    {
                        //中断线程
                        mythread.Interrupt();
                        //终止线程
                        mythread.Abort();
                        State = true;
                        this.BtnStart.Text = "启动监听";
                        this.Messagetxt.Text = "服务已关闭,等待开启...";
                    }
                }
                catch (Exception ex)
                {
                    DAL.Log.Write(DateTime.Now + ex.ToString() + "\r\n\r\n");
                }
                finally
                {
                    //退出对于线程的锁定
                    Monitor.Exit(threadlock);
                }
            }
      

  4.   

      /// <summary>
            /// 启动监听,轮询监听客户机请求并将客户端套接字存入转发表
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param> 
            private void Listen()
            {
                IPAddress _ip = IPAddress.Any;
                Socket newsoc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                newsoc.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
                IPEndPoint locaEp = new IPEndPoint(IPAddress.Any, _port);//建立连接
                try
                {
                    newsoc.Bind(locaEp);
                    newsoc.Listen(100);
                    newsoc.BeginAccept(new AsyncCallback(onCall), newsoc);//异步监听回调
                }
                catch (Exception ex)
                {
                    DAL.Log.Write(DateTime.Now.ToString() + ex.ToString() + "\r\n\r\n");
                }
            }        /// <summary>
            /// 监听回调
            /// </summary>
            /// <param name="ar"></param>
            private void onCall(IAsyncResult ar)
            {
                try
                {
                    Socket serverSoc = (Socket)ar.AsyncState;
                    Socket clent = serverSoc.EndAccept(ar);
                    byte[] comes = new byte[1024];
                    EndPoint enp = clent.RemoteEndPoint;
                    clent.Send(comes, comes.Length, 0);
                    _transmit_tb.Add(clent.RemoteEndPoint, null);
                    serverSoc.BeginAccept(new AsyncCallback(onCall), serverSoc);
                    while (true)
                    {
                        byte[] buffer = new byte[1024];
                        int re = clent.Receive(comes);
                        clent.Send(Encoding.ASCII.GetBytes("ok!"));
                        string msg = Encoding.UTF8.GetString(comes, 0, re);
                        string ip = clent.RemoteEndPoint.ToString();
                        if (msg.Length == 0)
                        {
                            _transmit_tb.Remove(clent.RemoteEndPoint);
                            _receviccethread.Interrupt();
                            _receviccethread.Abort();
                            break;
                        }                    ArrayList MessageRet = BLL.ClientLib.AdapterFactory.Prepare(msg, ip);//转入适配器并返回解析后数据                    if (MessageRet != null)
                        {
                            BLL.ClientLib.ResloveBuffer resbuf = new BLL.ClientLib.ResloveBuffer();
                            resbuf.Prepare(MessageRet[0].ToString(), ip);//将数据二次解析后保存数据库
                        }
                    }
                }
                catch (Exception ex)
                {
                    DAL.Log.Write(DateTime.Now.ToString() + ex.ToString() + "\r\n\r\n");
                }
            }        /// <summary>
            /// 执行定时查询设备状态
            /// </summary>
            /// <param name="source"></param>
            /// <param name="e"></param>
            public void theout(object source, System.Timers.ElapsedEventArgs e)
            {
                try
                {
                    DAL.DeviceinfoDataSetTableAdapters.DEVICEINFOTableAdapter da = new DAL.DeviceinfoDataSetTableAdapters.DEVICEINFOTableAdapter();
                    da.P_UPDSTATEBYTIME(_spandate);
                }
                catch (Exception ex)
                {
                    DAL.Log.Write(DateTime.Now + "\0" + ex + "\0\t\n");
                }
            }
      

  5.   


    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;namespace ASYCLINET
    {
        class Program
        {
            public int num=1;
            static void Main(string[] args)
            {
                TCPCLIENT Localclient = new TCPCLIENT();            Console.ReadLine();        }    }
        public class TCPCLIENT
        {
            public int num=1;
            public string msg;
            public byte[] buffer;        public IPEndPoint localip;
            public TcpClient tcpclient;        public TCPCLIENT()
            {
                localip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2241);//本地IP加端口
                tcpclient = new TcpClient(localip);
                tcpclient.Connect("127.0.0.1", 2230);//远程IP加端口            buffer = new byte[5];            System.Timers.Timer atimer = new System.Timers.Timer(500);//初始化一个TIMER类,时间间隔500MS
                atimer.Elapsed += new System.Timers.ElapsedEventHandler(TimerEvent);
                atimer.Enabled = true;
            }        private void TimerEvent(object Sender, EventArgs e)
            {
                if (num < 10)
                {
                    num = num + 1;
                    msg = "asd";
                    buffer = System.Text.Encoding.Default.GetBytes(msg);
                    tcpclient.Client.Send(buffer);
                    //Console.WriteLine("TIMER CIRCLE!");
                }        }    }
    }    }
    }