2011年5月19日

事件和委托在通信编程中的应用

封装后的socket类

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Text;
  4 using System.Net.Sockets;
  5 using System.Net;
  6 
  7 namespace SICOMSocket
  8 {
  9     public class SocketAsyncServer
 10     {
 11 
 12         public delegate void ProcessMessageeDelegate(Socket clientSock, byte[] msgBuff, DateTime getDataTime);
 13         public event ProcessMessageeDelegate ProcessMessageeEnvent;
 14 
 15         public delegate void ClearFlag();
 16         public event ClearFlag Clear;
 17 
 18         public delegate void NewConnectDelegate(string IP, string port, Socket clinetSocket);
 19         public event NewConnectDelegate NewConnectEnvent;
 20 
 21         public delegate void ClientShutDownDelegate(string IP, string port);
 22         public event ClientShutDownDelegate ClientShutDownEnvent;
 23 
 24 
 25         private Socket serverSock;
 26         byte[] msgBuff = new byte[1024];
 27 
 28         public void Start(int port)
 29         {
 30             try
 31             {
 32                 serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 33                 serverSock.Bind(new IPEndPoint(IPAddress.Any, port));
 34                 serverSock.Listen(10);
 35                 Console.WriteLine("开始监听端口" + port + "......");
 36                 serverSock.BeginAccept(new AsyncCallback(OnConnectRequest), serverSock);
 37             }
 38             catch (Exception ex)
 39             {
 40                 Console.WriteLine("监听端口" + port + "失败,请检查该端口是否被占用! " + ex.Message);
 41             }
 42         }
 43 
 44         public void OnConnectRequest(IAsyncResult ar)
 45         {
 46             try
 47             {
 48                 Socket listenerSock = (Socket)ar.AsyncState;
 49                 NewConnection(listenerSock.EndAccept(ar));
 50                 listenerSock.BeginAccept(new AsyncCallback(OnConnectRequest), listenerSock);
 51                 Console.WriteLine("已接受远程连接!");
 52             }
 53             catch (Exception ex)
 54             {
 55                 Console.WriteLine("新链接创建错误:" + ex.Message);
 56             }
 57         }
 58 
 59         private void NewConnection(Socket clientSock)
 60         {
 61             try
 62             {
 63                 EndPoint tempRemoteEP = clientSock.RemoteEndPoint;
 64                 IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
 65                 string rempip = tempRemoteIP.Address.ToString();
 66                 string remoport = tempRemoteIP.Port.ToString();
 67                 NewConnectEnvent(rempip, remoport, clientSock);
 68                 Clear();
 69                 AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
 70                 clientSock.BeginReceive(msgBuff, 0, msgBuff.Length, SocketFlags.None, recieveData, clientSock);
 71             }
 72             catch (Exception ex)
 73             {
 74                 Console.WriteLine("接收回调函数设置失败 {0}", ex.Message);
 75             }
 76         }
 77 
 78         public void OnRecievedData(IAsyncResult ar)
 79         {
 80             Socket sock = (Socket)ar.AsyncState;
 81             try
 82             {
 83                 DateTime getDataTime = DateTime.Now;
 84                 int nBytesRec = sock.EndReceive(ar);
 85                 if (nBytesRec > 0)
 86                 {
 87                     byte[] recievedNowBuff = new byte[nBytesRec];
 88                     Array.Copy(msgBuff, recievedNowBuff, nBytesRec);
 89                     try
 90                     {
 91                         AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
 92                         sock.BeginReceive(msgBuff, 0, msgBuff.Length, SocketFlags.None, recieveData, sock);
 93                     }
 94                     catch (Exception ex)
 95                     {
 96                         Console.WriteLine("接收回调函数设置失败 {0}", ex.Message);
 97                     }
 98 
 99                     System.Threading.Thread t1 = new System.Threading.Thread(delegate() { ProcessMessageeEnvent(sock, recievedNowBuff, getDataTime); });
100                     t1.Start();
101                 }
102                 else
103                 {
104                     Console.WriteLine("连接中断 {0}", sock.RemoteEndPoint);
105                     EndPoint tempRemoteEP = sock.RemoteEndPoint;
106                     IPEndPoint tempRemoteIP = (IPEndPoint)tempRemoteEP;
107                     string rempip = tempRemoteIP.Address.ToString();
108                     string remoport = tempRemoteIP.Port.ToString();
109                     sock.Shutdown(SocketShutdown.Both);
110                     sock.Close();
111                     ClientShutDownEnvent(rempip, remoport);
112                 }
113             }
114             catch (Exception ex)
115             {
116                 Console.WriteLine(ex.Message, "未知错误!");
117             }
118         }
119     }
120 
121 }

调用类:

 

 SICOMSocket.SocketAsyncServer SAC = new SICOMSocket.SocketAsyncServer();
        
byte ServerID;
        
public void Start(byte ServerID)
        {
            
this.ServerID = ServerID;
            SAC.ClientShutDownEnvent 
+= new SICOMSocket.SocketAsyncServer.ClientShutDownDelegate(SAC_ClientShutDownEnvent);
            SAC.NewConnectEnvent 
+= new SICOMSocket.SocketAsyncServer.NewConnectDelegate(SAC_NewConnectEnvent);
            SAC.ProcessMessageeEnvent 
+= new SICOMSocket.SocketAsyncServer.ProcessMessageeDelegate(SAC_ProcessMessageeEnvent);
            SAC.Start(
502);
        }
void SAC_NewConnectEnvent(string IP, string port, System.Net.Sockets.Socket clinetSocket)
        {
            Console.WriteLine(DateTime.Now.ToString() 
+ "监听到一个新的连接:对方IP[" + IP + "]" + "对方端口[" + port + "]");
        }

        
void SAC_ClientShutDownEnvent(string IP, string port)
        {
            Console.WriteLine(DateTime.Now.ToString() 
+ "连接中断:对方IP[" + IP + "]" + "对方端口[" + port + "]");
        }

 

posted @ 2011-05-19 23:33 badnewfish 阅读(50) 评论(0) 编辑

WPF学习笔记--运行时画图的实现

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

namespace Main.Ranging
{
    public class Ruler
    {
        public delegate void PolygonAddedDelegate(Polygon Points);
        public event PolygonAddedDelegate PolygonAddedEvent;

        UInt16 AreaTempCount = 0;
        double Sum = 0;//距离
        Point mousePosition; //鼠标坐标
        bool TrunOn_OffSwitch = false;//测距开关量
        bool RulerKey = false;//标尺显示开关量
        double Ruler_X = 0;//顶点X值
        double Ruler_Y = 0;//顶点Y值
        double movePlank_X = 0;
        double movePlank_Y = 0;
        UC_Ruler UC_ruler = new UC_Ruler();
        Canvas RulerBoard;
        Canvas MovePlank;
        double zoomValue = 1;
        PointCollection PointListTemp = new PointCollection();
        Polygon MyPolygon = new Polygon();
        bool _Eraser = false;
        /// <summary>
        /// 用于判断操作类型的开关
        /// </summary>
        public bool Eraser
        {
            get { return _Eraser; }
            set { _Eraser = value; }
        }

        public double ZoomValue
        {
            get { return zoomValue; }
            set { zoomValue = value; }
        }
        double x_cut, y_cut;
        /// <summary>
        ///
        /// </summary>
        /// <param name="movePlank"></param>
        /// <param name="rulerBoard">要计算的底层面板</param>
        /// <param name="x_cut">绝对坐标偏差</param>
        /// <param name="y_cut">相对坐标偏差</param>
        public Ruler(Canvas movePlank, Canvas rulerBoard, double x_cut, double y_cut)
        {
            this.x_cut = x_cut;
            this.y_cut = y_cut;
            this.MovePlank = movePlank;
            this.RulerBoard = rulerBoard;
            movePlank.MouseMove += new MouseEventHandler(RulerBoard_MouseMove);
            movePlank.MouseLeftButtonDown += new MouseButtonEventHandler(RulerBoard_MouseLeftButtonDown);
            movePlank.MouseRightButtonDown += new MouseButtonEventHandler(RulerBoard_MouseRightButtonDown);
            MovePlank.MouseWheel += new MouseWheelEventHandler(RulerBoard_MouseWheel);
            //PointListTemp.Add(new PointCollection());
            init();
        }
        private void init()
        {
            TrunOn_OffSwitch = false;//测距开关量
            RulerKey = false;//标尺显示开关量
            Ruler_X = 0;//顶点X值
            Ruler_Y = 0;//顶点Y值
            Sum = 0;//距离
            //RulerBoard.Width = 3300;
            //RulerBoard.Height = 2200;
        }
        public void AddElement(UserControl element, double x, double y)
        {
            Canvas.SetTop(element, y);
            Canvas.SetLeft(element, x);
            RulerBoard.Children.Add(element);
        }
        /// <summary>
        /// 开始测量或关闭测量
        /// </summary>
        /// <param name="TrunOn_Off">true为开false为关</param>
        public void RulerSwitch(bool TrunOn_Off)
        {
            TrunOn_OffSwitch = TrunOn_Off;
        }
        private void RulerBoard_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!_Eraser)
            {
                if (TrunOn_OffSwitch)
                {
                    if (RulerKey)
                    {
                        RulerBoard.Children.Remove(UC_ruler);
                        RulerKey = !RulerKey;
                    }
                    mousePosition = e.GetPosition(null);
                    UC_Coordinates coordinates = new UC_Coordinates();
                    //addElement(coordinates, (mousePosition.X - movePlank_X) / zoomValue, (mousePosition.Y - movePlank_Y) / zoomValue);
                    AddElement(coordinates, (mousePosition.X - movePlank_X - x_cut) / zoomValue, (mousePosition.Y - movePlank_Y - y_cut) / zoomValue);
                    PointListTemp.Add(new Point((mousePosition.X - movePlank_X - x_cut) / zoomValue, (mousePosition.Y - movePlank_Y - y_cut) / zoomValue));

                    string text = "起  点";
                    if (Ruler_X == 0 && Ruler_Y == 0)
                    {
                        //Ruler_X = (mousePosition.X - movePlank_X) / zoomValue;
                        //Ruler_Y = (mousePosition.Y - movePlank_Y) / zoomValue;
                        Ruler_X = (mousePosition.X - x_cut - movePlank_X) / zoomValue;
                        Ruler_Y = (mousePosition.Y - movePlank_Y - y_cut) / zoomValue;
                        coordinates.setValue(text);
                        return;
                    }
                    //Point startPt = new Point(Ruler_X, Ruler_Y);
                    //Sum += setDifference((mousePosition.X - movePlank_X) / zoomValue, (mousePosition.Y - movePlank_Y) / zoomValue);
                    Sum += setDifference((mousePosition.X - movePlank_X - x_cut) / zoomValue, (mousePosition.Y - movePlank_Y - y_cut) / zoomValue);
                    text = Sum.ToString() + "米";
                    coordinates.setValue(text);
                    //Point endPt = new Point((mousePosition.X - movePlank_X) / zoomValue, (mousePosition.Y - movePlank_Y) / zoomValue);
                    //Ruler_X = (mousePosition.X - movePlank_X) / zoomValue;
                    //Ruler_Y = (mousePosition.Y - movePlank_Y) / zoomValue;
                    //Point endPt = new Point((mousePosition.X - movePlank_X - x_cut) / zoomValue, (mousePosition.Y - movePlank_Y - y_cut) / zoomValue);
                    Ruler_X = (mousePosition.X - movePlank_X - x_cut) / zoomValue;
                    Ruler_Y = (mousePosition.Y - movePlank_Y - y_cut) / zoomValue;
                    //DrawingLine(startPt, endPt);

 

                    for (int i = 0; i < RulerBoard.Children.Count; i++)
                    {
                        FrameworkElement element = RulerBoard.Children[i] as FrameworkElement;
                        if (element.Tag != null)
                            if ("TempPolygon" == element.Tag.ToString())
                            {
                                RulerBoard.Children.RemoveAt(i);
                                break;
                            }
                    }

                    MyPolygon.Stroke = System.Windows.Media.Brushes.Black;
                    MyPolygon.Fill = System.Windows.Media.Brushes.LightSeaGreen;
                    MyPolygon.StrokeThickness = 2;
                    MyPolygon.HorizontalAlignment = HorizontalAlignment.Left;
                    MyPolygon.VerticalAlignment = VerticalAlignment.Center;
                    MyPolygon.Points = PointListTemp;
                    MyPolygon.Tag = "TempPolygon";
                    RulerBoard.Children.Add(MyPolygon);

                }
            }
        }
        private void RulerBoard_MouseMove(object sender, MouseEventArgs e)
        {
            if (!_Eraser)
            {
                if (TrunOn_OffSwitch)
                {
                    string text = "单击确定起点";
                    FrameworkElement element = MovePlank as FrameworkElement;
                    movePlank_X = (double)element.GetValue(Canvas.LeftProperty);
                    movePlank_Y = (double)element.GetValue(Canvas.TopProperty);
                    mousePosition = e.GetPosition(null);
                    if (!RulerKey)
                    {

                        //addElement(UC_ruler, (mousePosition.X - movePlank_X) / zoomValue, (mousePosition.Y - movePlank_Y) / zoomValue);
                        AddElement(UC_ruler, (mousePosition.X - movePlank_X - x_cut) / zoomValue, (mousePosition.Y - movePlank_Y) / zoomValue);
                        RulerKey = !RulerKey;
                    }
                    //UC_ruler.SetValue(Canvas.LeftProperty, (mousePosition.X - movePlank_X) / zoomValue);
                    //UC_ruler.SetValue(Canvas.TopProperty, (mousePosition.Y - movePlank_Y) / zoomValue);
                    UC_ruler.SetValue(Canvas.LeftProperty, (mousePosition.X - movePlank_X - x_cut) / zoomValue);
                    UC_ruler.SetValue(Canvas.TopProperty, (mousePosition.Y - movePlank_Y) / zoomValue);
                    if (Ruler_X == 0 && Ruler_Y == 0)
                    {
                        UC_ruler.setValue(text);
                        return;
                    }
                    //double str = Sum + setDifference(mousePosition.X / zoomValue, mousePosition.Y / zoomValue);
                    double str = Sum + setDifference((mousePosition.X - movePlank_X - x_cut) / zoomValue, (mousePosition.Y - movePlank_X) / zoomValue);
                    text = "总长:" + str.ToString() + "米";
                    UC_ruler.setValue(text);
                    e.Handled = true;
                }
            }
        }
        private void RulerBoard_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (!_Eraser)
            {
                if (PointListTemp.Count > 0)
                    PolygonAddedEvent(MyPolygon);
                //RulerBoard.Children.Remove(UC_ruler);
                //init();
                //PointListTemp.Clear();
            }
        }
        private void RulerBoard_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            FrameworkElement element = MovePlank as FrameworkElement;
            movePlank_X = (double)element.GetValue(Canvas.LeftProperty);
            movePlank_Y = (double)element.GetValue(Canvas.TopProperty);
            //ruler.SetValue(Canvas.LeftProperty, (mousePosition.X - movePlank_X) / zoomValue);
            //ruler.SetValue(Canvas.TopProperty, (mousePosition.Y - movePlank_Y) / zoomValue);
            UC_ruler.SetValue(Canvas.LeftProperty, (mousePosition.X - x_cut - movePlank_X) / zoomValue);
            UC_ruler.SetValue(Canvas.TopProperty, (mousePosition.Y - y_cut - movePlank_Y) / zoomValue);
            e.Handled = true;

        }
        private double setDifference(double x, double y)
        {
            return Math.Round(Math.Sqrt(Math.Pow(x - Ruler_X, 2) + Math.Pow(y - Ruler_Y, 2)), 2);
        }
        //划线
        protected void DrawingLine(Point startPt, Point endPt)
        {
            LineGeometry myLineGeometry = new LineGeometry();
            myLineGeometry.StartPoint = startPt;
            myLineGeometry.EndPoint = endPt;
            Path myPath = new Path();
            myPath.Stroke = Brushes.Red;
            myPath.StrokeThickness = 2;
            myPath.Data = myLineGeometry;
            RulerBoard.Children.Add(myPath);
        }
        public void ClearAll()
        {
            init();
            RulerBoard.Children.Clear();
        }

        public void AddNewArea()
        {
            PointListTemp.Clear();
            //AreaTempCount++;
        }
    }
}

 

posted @ 2011-05-19 23:23 badnewfish 阅读(120) 评论(1) 编辑

WPF学习笔记--一些新鲜的控件

System.Windows.Controls.ComboBox 之数据绑定:

绑定到DataTable

DataTable DTDepartments = new BLL.DepartmentT().GetAll();
comboBoxAllDepartments.ItemsSource
= DTDepartments.Rows;

 

posted @ 2011-05-19 23:19 badnewfish 阅读(30) 评论(0) 编辑

导航

<2011年5月>
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

公告


点击这里给我发消息 
北京礼品网

巴顿的博客

昵称:badnewfish
园龄:5年3个月
粉丝:2
关注:0

搜索

 

常用链接

我的标签

随笔分类

随笔档案

相册

最新评论

阅读排行榜

评论排行榜

推荐排行榜