zoukankan      html  css  js  c++  java
  • C# Stock 编程 TCP 、委托、多线程

    • 服务器端

        1、开启监听

    //开启监听
    private void button1_Click(object sender, EventArgs e)
            {
                //当点击开始监听的时候 在服务器端创建一个负责监听IP地址和端口号的Socket
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //获取ip地址
                IPAddress ip = IPAddress.Parse(this.txt_IP.Text.Trim());
                //创建端口号
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(this.txt_Port.Text.Trim()));
                //绑定IP地址和端口号
                socketWatch.Bind(point);
                
                //开始监听:设置最大可以同时连接多少个请求
                socketWatch.Listen(10);
                this.txt_Log.AppendText("监听成功" + " 
     
    ");
                //实例化回调
                setCallBack = new SetTextValueCallBack(SetTextValue); //修改textbox
                receiveCallBack = new ReceiveMsgCallBack(ReceiveMsg); //修改textbox
                setCmbCallBack = new SetCmbCallBack(AddCmbItem);      //修改combox
                sendCallBack = new SendFileCallBack(SendFile);         //发送信息
                //创建线程
                AcceptSocketThread = new Thread(new ParameterizedThreadStart(StartListen));  //创建监听参数{监听}
                AcceptSocketThread.IsBackground = true;
                AcceptSocketThread.Start(socketWatch);
    
            }
    
     /// <summary>
            /// 监听等待PC端的连接,创建通信用的Socket
            /// </summary>
            /// <param name="obj"></param>
            private void StartListen(object obj)
            {
                Socket socketWatch = obj as Socket;
               
                    //等待客户端的连接,并且创建一个用于通信的Socket
                    socketSend = socketWatch.Accept();
                    //获取远程主机的ip地址和端口号
                    string strIp = socketSend.RemoteEndPoint.ToString();
                    dicSocket.Add(strIp, socketSend);
                    this.cmb_Socket.Invoke(setCmbCallBack, strIp);//将远程主机ip地址及 通讯Socket添加到combox
                    string strMsg = "远程主机:" + socketSend.RemoteEndPoint + "连接成功";
                    //使用回调
                    txt_Log.Invoke(setCallBack, strMsg);
    
                    //定义接收客户端消息的线程
                    Thread threadReceive = new Thread(new ParameterizedThreadStart(Receive));
                    threadReceive.IsBackground = true;
                    threadReceive.Start(socketSend);
    
                
            }
    
          /// <summary>
            ///监听消息
            /// </summary>
            /// <param name="obj"></param>
            private void Receive(object obj)
            {
                Socket socketSend = obj as Socket;
             
                   
                    //客户端连接成功后,服务器接收客户端发送的消息
                    byte[] buffer = new byte[1024*100];
                    //实际接收到的有效字节数
                    
                        int count = socketSend.Receive(buffer);
                
                    if (count == 0)//count 表示客户端关闭,要退出循环
                    {
                      
                    }
                    else
                    {
                        string str = Encoding.Default.GetString(buffer, 0, count);
                        string strReceiveMsg = "接收:" + socketSend.RemoteEndPoint + "发送的消息:" + str;
                        txt_Log.Invoke(receiveCallBack, strReceiveMsg);
                    }
                
            }
    View Code

        2、发送消息

            /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button5_Click(object sender, EventArgs e)
            {
                try
                {
                    string strMsg = this.txt_Msg.Text.Trim();
                    byte[] buffer = Encoding.Default.GetBytes(strMsg);
                    List<byte> list = new List<byte>();
                    list.Add(0);
                    list.AddRange(buffer);
                    //将泛型集合转换为数组
                    byte[] newBuffer = list.ToArray();
                    //获得用户选择的IP地址
                    string ip = this.cmb_Socket.SelectedItem.ToString();
                    dicSocket[ip].Send(newBuffer);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("给客户端发送消息出错:" + ex.Message);
                }
    
            }
    View Code

         3、停止监听

            /// <summary>
            /// 停止监听
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button2_Click(object sender, EventArgs e)
            {
    
                socketWatch.Close();
                socketSend.Close();
                AcceptSocketThread.Abort();
                threadReceive.Abort(); 
            }
    View Code
    • 客户端

    1、连接服务器

        /// <summary>
            /// 连接服务器
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPAddress ip = IPAddress.Parse(this.txt_IP.Text.Trim());
                    socketSend.Connect(ip, Convert.ToInt32(this.txt_Port.Text.Trim()));
                    //实例化回调
                    setCallBack = new SetTextCallBack(SetValue);
                    receiveCallBack = new ReceiveMsgCallBack(SetValue);
                    this.txt_Log.Invoke(setCallBack, "连接成功");
    
                    //开启一个新的线程不停的接收服务器发送消息的线程
                    threadReceive = new Thread(new ThreadStart(Receive));
                    //设置为后台线程
                    threadReceive.IsBackground = true;
                    threadReceive.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("连接服务端出错:" + ex.ToString());
                }
    
            }
    View Code

    2、发送消息

           /// <summary>
            /// 发送消息
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void button3_Click(object sender, EventArgs e)
            {
                try
                {
                    string strMsg = this.txt_Msg.Text.Trim();
                    byte[] buffer = new byte[2048];
                    buffer = Encoding.Default.GetBytes(strMsg);
                    int receive = socketSend.Send(buffer);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("发送消息出错:" + ex.Message);
                }
    
            }
    View Code

    3、接收消息

    /// <summary>
            /// 监听服务器发送消息
            /// </summary>
            private void Receive()
            {
                try
                {
               
                        byte[] buffer = new byte[2048];
                        //实际接收到的字节数
                        int r = socketSend.Receive(buffer);
                        if (r == 0)
                        {
                  
                        }
                        else
                        {
                            //判断发送的数据的类型
                            if (buffer[0] == 0)//表示发送的是文字消息
                            {
                                string str = Encoding.Default.GetString(buffer, 1, r - 1);
                                this.txt_Log.Invoke(receiveCallBack, "接收远程服务器:" + socketSend.RemoteEndPoint + "发送的消息:" + str);
                            }
                            //表示发送的是文件
                            if (buffer[0] == 1)
                            {
                                if (buffer[1] == 0)
                                {
                                    SaveFileDialog sfd = new SaveFileDialog();
                                    sfd.InitialDirectory = @"";
                                    sfd.Title = "请选择要保存的文件";
                                    sfd.Filter = "所有文件|*.*";
                                    sfd.ShowDialog(this);
                                    strPath = sfd.FileName;
                                }
                                using (FileStream fsWrite = new FileStream(strPath, FileMode.OpenOrCreate, FileAccess.Write))
                                {
                                    fsWrite.Write(buffer, 2, r - 2);
                                }
    
                                MessageBox.Show("保存文件成功");
                            }
                        
    
    
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("接收服务端发送的消息出错:" + ex.ToString());
                }
            }
    View Code

    4、断开连接

               //关闭socket
                socketSend.Close();
                //终止线程
                threadReceive.Abort();
    View Code
  • 相关阅读:
    WebService
    JavaMail
    ssh框架整合
    CSS3初步
    SpringMVC 文件上传及下载
    Java多线程
    SpringMVC 数据校验
    初始化参数绑定——日期格式
    SpringMVC入门
    Quartz
  • 原文地址:https://www.cnblogs.com/apimeng/p/9566159.html
Copyright © 2011-2022 走看看