读书人

关于UDP的 !

发布时间: 2012-07-28 12:25:13 作者: rapoo

关于UDP的 求助!!!
服务器端的代码如下:
public class Class1
{
static void Main(string[] args)
{
Custom.StartListener();
}
}
public class Custom
{
private static readonly IPAddress GroupAddress = IPAddress.Parse("127.0.0.1");
private const int GroupPort = 11000;

public static void StartListener()
{
//bool done = false;
UdpClient listener = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
try
{
//listener.JoinMulticastGroup(GroupAddress);
listener.Connect("127.0.0.1",11000);
while (true)
{
Console.WriteLine("Waiting for broadcast");
byte[] bytes = listener.Receive(ref groupEP);
Console.WriteLine("Received broadcast from {0} :\n {1}\n",
groupEP.Address.ToString(),
Encoding.ASCII.GetString(bytes, 0, bytes.Length));
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

}

客户端的代码:
public class Client
{
static void Main(string[] args)
{
Console.WriteLine("输入数据");
Send(Console.ReadLine());
Console.ReadLine();
}

private static IPAddress GroupAddress = IPAddress.Parse("127.0.0.1");
private static int GroupPort = 11000;
private static void Send(string message)
{
UdpClient sender = new UdpClient();
IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);

try
{
Console.WriteLine("Sending datagram : {0}", message);
byte[] bytes = Encoding.ASCII.GetBytes(message);
sender.Send(bytes, bytes.Length, "192.168.0.16", 4567);
sender.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}

}

现在有问题了,我服务器接收不到数据。。求大侠指教啊。。小弟先行感谢了,!

[解决办法]
客户端不要指定端口,而且你这服务端和客户端端口都一样,肯定不行的
[解决办法]
Connect 是发送用的

C# code
// 服务端方法public static void StartListener(){    UdpClient listener = new UdpClient(GroupPort);    IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);    try    {        while (true)        {            Console.WriteLine("Waiting for broadcast");            byte[] bytes = listener.Receive(ref groupEP);            Console.WriteLine("Received broadcast from {0} :\n {1}\n",            groupEP.Address.ToString(),            Encoding.ASCII.GetString(bytes, 0, bytes.Length));        }    }    catch (Exception e)    {        Console.WriteLine(e.ToString());    }}// 客户端方法private static void Send(string message){    UdpClient sender = new UdpClient();    IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);    try    {        Console.WriteLine("Sending datagram : {0}", message);        byte[] bytes = Encoding.ASCII.GetBytes(message);        sender.Send(bytes, bytes.Length, groupEP);        sender.Close();    }    catch (Exception e)    {        Console.WriteLine(e.ToString());    }} 


[解决办法]

探讨
谢谢。。我在本机上可以服务器可以获取到了。但是我把服务器放在另外一台电脑上就获取不到了。。,

读书人网 >C#

热点推荐