读书人

C#广播有关问题

发布时间: 2012-05-10 16:02:39 作者: rapoo

C#广播问题
大家看下面的代码,这是我在网上摘下来的。
我用这段代码的时候出现一种状况,当我没有联网的时候,acc接收到的信息是从本地IP发出的,局域网的主机2也能接收到信息。但是如果我连接到网络,那它显示的就是外网的IP了,而且只有本机才接收得到这些信息,局域网内的主机2接收不到。这样就实现不了我想要的功能了。
如果这个方法行不通,请给我一些其他的方法。
我想要的功能就是,主机N开机之后搜索局域网内的其它主机,告诉其它主机它上线了。其它主机收到消息后向它发出一些回复信息。
万分感谢!!~~

C# code
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using System.Net;using System.Threading;using System.Net.Sockets;namespace UDP广播2{    public partial class Form1 : Form    {        public Form1()        {            InitializeComponent();            Control.CheckForIllegalCrossThreadCalls = false;//允许交差线程访问(没这个就不能在别的进程修改textBox了)        }        EndPoint ep;        string receiveData;        Socket socket;        private void Acc()        {            socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);            IPEndPoint iep = new IPEndPoint(IPAddress.Any, 8899);            socket.Bind(iep);            ep = (EndPoint)iep;            byte[] bytes = new byte[1024];            byte[] initbytes = new byte[1024];            while (true)            {                try                {                    initbytes.CopyTo(bytes,0);                    socket.ReceiveFrom(bytes, ref ep);                    receiveData = System.Text.Encoding.Unicode.GetString(bytes);                    receiveData = receiveData.TrimEnd('\u0000');                    if (receiveData.Length > 0)                    {                        richTextBox1.Text = "来自" + ep.ToString() + "的消息" + receiveData;                    }                }                catch                {                    break;                }            }        }        private void Form1_FormClosing(object sender, FormClosingEventArgs e)        {            socket.Close();        }        Socket socket2 = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);//只能用UDP协议发送广播,所以ProtocolType设置为UDP        IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 8899);                                //让其自动提供子网中的IP地址        byte[] bytes;        private void button2_Click(object sender, EventArgs e)        {                        bytes = Encoding.Unicode.GetBytes(textBox1.Text);                    //将发送内容转换为字节数组            textBox1.Text = "";            socket2.SendTo(bytes, iep);        }        private void button1_Click(object sender, EventArgs e)        {            socket2.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);           //设置broadcast值为1,允许套接字发送广播信息            button1.Enabled = false;            Thread th = new Thread(new ThreadStart(Acc));            th.Start();        }    }}


[解决办法]
把防火墙关了,在运行里Services.msc,然后把Windows firewall的禁掉。

读书人网 >C#

热点推荐