我正在学习如何使用UDP
与同一台机器上的其他应用程序进行通信,因此我正在通过下面的程序来获取这些概念,但是当我运行它时,出现错误消息,他说:C#简单的UDP通信
型 'System.Net.Sockets.SocketException' 未处理的异常发生在System.dll中
我缺少什么或者做错了吗?有人可以请简单解释一下如果程序运行会发生什么?谢谢
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
namespace udpClient
{
public class Program
{
public static void Main(string[] args)
{
byte[] data = new byte[1024];
string input, stringData;
IPEndPoint ipep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string welcome = "Hello, are you there?";
data = Encoding.ASCII.GetBytes(welcome);
server.SendTo(data, data.Length, SocketFlags.None, ipep);
IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
EndPoint Remote = (EndPoint)sender;
data = new byte[1024];
int recv = server.ReceiveFrom(data, ref Remote);
Console.WriteLine("Message received from {0}:", Remote.ToString());
Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
// In Unity3D, replace this with update or coroutine.
while (true)
{
input = Console.ReadLine();
if (input == "exit")
break;
server.SendTo(Encoding.ASCII.GetBytes(input), Remote);
data = new byte[1024];
recv = server.ReceiveFrom(data, ref Remote);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);
}
Console.WriteLine("Stopping client ..");
server.Close();
// Console.WriteLine("\nPress any key ...");
// Console.ReadKey();
}
}
}
检查:http://stackoverflow.com/questions/2370388/socketexception-address-incompatible-with-requested-protocol –
什么是完整的错误消息,并在哪一行是上调? –
@Rahul这个例子是这个异常的_many_原因之一。 OP需要检查他们的InnerException。 – CodeCaster