• Socket收发信息


    List<Socket> SocketClientList = new List<Socket>();
    public Form2()
    {
    InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
    Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IPEndPoint ipEndpoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5555);
    serverSocket.Bind(ipEndpoint);
    serverSocket.Listen(10);
    ThreadPool.QueueUserWorkItem(new WaitCallback(GetAccept), serverSocket);


    }

    private void GetAccept(object state)
    {
    Socket serverSocket = state as Socket;
    while (true)
    {
    Socket socketClient = serverSocket.Accept();
    socketClient.Send(Encoding.Default.GetBytes("收到一个连接————"));
    SocketClientList.Add(socketClient);
    ThreadPool.QueueUserWorkItem(new WaitCallback(ReceiveData), socketClient);
    }
    }
    private void ReceiveData(object obj) {
      Socket socketClient = obj as Socket;
      byte[] buffer = new byte[1024*1024];

      while (true) {

        int l=0; 
      try //捕获异常退出
      {
        l= socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None);

      }
      catch {

        SocketClientList.Remove(socketClient);    

        return;

        //异常退出

      }
        //在退出前会发送一个字消息 正常退出
        if (l == 0)
        {
          socketClient.Shutdown(SocketShutdown.Both);
          socketClient.Close();
          SocketClientList.Remove(socketClient);

          return;
        }
        string msgfromclient = Encoding.Default.GetString(buffer, 0, l);
      
      //在下面添加收到消息的逻辑
      }
    }
    private void button2_Click(object sender, EventArgs e)
    {
      foreach (Socket socket in SocketClientList)

       {

        if(socket.Connected)

        {

          socket.Send(Encoding.Default.GetBytes(("data" + DateTime.Now.ToString())));

        }
        
      }
    }

  • 相关阅读:
    让你平步青云的10个谈话技巧
    瑞士心理学家和精神分析医师――荣格
    市场倍增理论
    淘宝网格,淘宝富人群
    波波的个人简历
    磁盘修复工具
    9种没结果的爱(未婚者必读)!!!
    网络投机市场
    网页数据抽取的方法介绍
    C#扩展方法试用
  • 原文地址:https://www.cnblogs.com/boentouch/p/12818181.html
Copyright © 2020-2023  润新知