我正在尝试在服务器收到" debug"时将数据发送回客户端。 ATM以下提供此错误:
不允许发送或接收数据的请求,因为套接字未连接且(使用sendto调用在数据报套接字上发送时)未提供地址。
添加了我的主要课程以帮助回答问题
static Socket newSocket;
static byte[] data;
static EndPoint tmpRemote;
static IPEndPoint sender, endpoint;
static int recv;
static void Main(string[] args)
{
data = new byte[1024];
endpoint = new IPEndPoint(IPAddress.Any, 3000);
newSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
newSocket.Bind(endpoint);
sender = new IPEndPoint(IPAddress.Any, 904);
tmpRemote = (EndPoint)sender;
newSocket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref tmpRemote, new AsyncCallback(OperatorCallBack), data);
Console.Read();
}
private static void OperatorCallBack(IAsyncResult ar)
{
log("[" + DateTime.Now + "][New Connection] " + tmpRemote.ToString() + "");
try
{
int size = newSocket.EndReceiveFrom(ar, ref tmpRemote);
if (size > 0)
{
data = (byte[])ar.AsyncState;
string[] dataCommand = Encoding.ASCII.GetString(data, 0, size).Split(' ');
if (dataCommand[0] == "debug")
{
newSocket.Send(Encoding.ASCII.GetBytes("HA IT WORKED :)"));
log("Sent debug");
}
else
{
log("Invalid Command");
}
}
data = new byte[1024];
newSocket.BeginReceiveFrom(data, 0, data.Length, SocketFlags.None, ref tmpRemote, new AsyncCallback(OperatorCallBack), data);
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
}
}
答案 0 :(得分:3)
尝试通过慢速连接连接到套接字时遇到类似问题。我通过在任何发送/接收呼叫之前确保newSocket.Connected属性为真来解决它。
答案 1 :(得分:2)
通过ProtocolType.Udp发送数据时不需要连接(socket.connect()) 当您不建议UDP消息应转发的地址时,可能会发生该错误
在您的情况下 here the address is not provided for udp Send()
<强>解强>
尝试使用SendTo()
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
soc.EnableBroadcast = true;
IPEndPoint ipend = new IPEndPoint(IPAddress.Broadcast, 58717);
EndPoint endp = (EndPoint)ipend;
byte[] bytes = new byte[1024];
bytes = Encoding.ASCII.GetBytes(str);
soc.SendTo(bytes,ipend);
soc.Close();
答案 2 :(得分:1)
错误信息非常清楚。您在未连接的套接字上调用send()而不提供目标地址。你在哪里发送? UDP不知道。