发送或接收数据的请求被禁止,因为在发送数据时套接字未连接
本文关键字:数据 因为 套接字 连接 请求 禁止 | 更新日期: 2023-09-27 18:00:10
当服务器接收到"调试"时,我正试图将数据发送回客户端。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);
}
}
我在尝试通过慢速连接连接到套接字时遇到了类似的问题。在进行任何发送/接收调用之前,我通过确保newSocket.Connected属性为true来解决此问题。
错误消息非常清楚。您在未连接的套接字上调用send(),但没有提供目标地址。你要寄往哪里?UDP不知道。
在您的情况下这里没有为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();