C# SocketUDP服务器,组播

admin2024-07-02  8

SocketUDP

自己即是服务器又是客户端 ,在发消息只需要改成对方ip和端口号即可

前提对方必须开启服务器 socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.107.72"), 8080));

控件:Button,TextBox,RichTextBox

打开自己服务器

public Form1()
{
    InitializeComponent();
    //1创建一个服务器 绑定的是ip和端口号 192.168.107.83, 8080
    // 张三的终端 以后谁想跟张三聊的时候 发这个ip和端口号
    socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
    socket.Bind(new IPEndPoint(IPAddress.Any, 8080));
    startReceive();
}
Socket socket;
void startReceive() 
{
    byte[] bs = new byte[1024];
    Task.Run(() =>
    {
        while (true)
        {
            int count = socket.Receive(bs);
            string s = Encoding.UTF8.GetString(bs,0, count);
            this.Invoke((Action)(() =>
            {
                richTextBox1.AppendText(s + "\t\n");
            }));

        }
    });
}

发送按钮事件

private void button1_Click(object sender, EventArgs e)
{
    //发消息的一定要注意iphe端口号
    socket.SendTo(Encoding.UTF8.GetBytes(this.textBox1.Text),
       new IPEndPoint(IPAddress.Parse("192.168.107.73"), 8082));
}

Socket组播服务器

C# SocketUDP服务器,组播,第1张

 public Form1()
 {
     InitializeComponent();
 }
 Socket socket;
 private void button1_Click(object sender, EventArgs e)
 {
     //1创建socket对象
    socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

     //2 绑定ip和端口号
     socket.Bind(new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8080));
    //3 加入组播地址
    //SetSocketOption 添加套接字可配置选项
    //参数1.支持协议类型,
    //参数2 添加组播地址的功能
    //参数3 要组播的地址
    socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
        new MulticastOption(IPAddress.Parse("224.0.0.188"))
        );

    //4以后大家要是接受的话 接受组内发来的消息的时候 必须添接受组内代码

    //5 接收数据
    startReceive();     
}
void startReceive()
{
    new Thread(() =>
    {
        byte[] buffer = new byte[1024];
        while (true)
        {
            int count = socket.Receive(buffer);
            string s = Encoding.UTF8.GetString(buffer, 0, count);
            richTextBox1.Invoke((Action)(() =>
            {
                richTextBox1.AppendText(s + "\t\n");
            }));
        }
    }).Start();
}

//发送消息
private void button2_Click(object sender, EventArgs e)
{
    //发消息指定组地址进行发送,以后要求接受消息端口号和此处端口号保持一致
    socket.SendTo(Encoding.UTF8.GetBytes(this.textBox1.Text),
          new IPEndPoint(IPAddress.Parse("224.0.0.188"), 10086)
          );
}

socket组播客户端

控件:

两个按钮(客户端打开接收消息,发送),textbox,richtextBox

        public Form1()
        {
            InitializeComponent();
        }

        Socket socket;
        private void button1_Click(object sender, EventArgs e)
        {
            //1创建socket对象
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            //2 绑定ip和端口号
            socket.Bind(new IPEndPoint(IPAddress.Any, 10086));

            //3 设置组地址 对客户端加入指定组播地址内
            socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership,
                new MulticastOption(IPAddress.Parse("224.0.1.188")));
          

            //4 接受消息
            Task.Run(() =>
            {
                while (true)
                {
                    byte[] buffer = new byte[1024];
                    //int count = socket.Receive(buffer);

                    EndPoint ip = new IPEndPoint(IPAddress.None, 0); //定义endpoint类型变量,终端类型
                    //ReceiveFrom()接受数据的方法 从哪个终端发来的消息
                    //参数3是发来消息的地址 类型是endpoint
                    int count = socket.ReceiveFrom(buffer, 0, ref ip);
                    IPEndPoint i1 = ip as IPEndPoint; // 把endpoint类型 转成IPEndPoint

                    string s = Encoding.UTF8.GetString(buffer, 0, count);
                    
                    richTextBox1.Invoke((Action)(() =>
                    {
                        richTextBox1.AppendText(i1.Address+":"+s + "\t\n");
                        richTextBox1.SelectionStart=richTextBox1.Text.Length; 
                        richTextBox1.ScrollToCaret();
                    }));

                }

            });
        }
        private void button2_Click(object sender, EventArgs e)
        {
            //socket.SendTo(Encoding.UTF8.GetBytes("hello world"),
            //    new IPEndPoint(IPAddress.Parse("192.168.107.83"), 8080));

            if (Encoding.UTF8.GetBytes(this.textBox1.Text).Length>1024)
            {
                return;
            }
            socket.SendTo(Encoding.UTF8.GetBytes(this.textBox1.Text),
               new IPEndPoint(IPAddress.Parse("224.0.1.188"), 10086));
        }

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!