[英]C# Socket connection error
I'm working with sockets in C# and I'm getting the following error: 我正在使用C#中的套接字,但是出现以下错误:
A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied 不允许发送或接收数据的请求,因为未连接套接字,并且(当使用sendto调用在数据报套接字上发送时)未提供地址
Here is the code that I'm executing: 这是我正在执行的代码:
private void HostSubscriberService()
{
IPAddress ipV4 = PublisherService.ReturnMachineIP();
var localEP = new IPEndPoint(ipV4, _port);
var server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(localEP);
StartListening(server);
}
private void StartListening(Socket server)
{
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
var data = new byte[1024];
int recv = server.ReceiveFrom(data, ref remoteEP);
string messageSendFromClient = Encoding.ASCII.GetString(data, 0, recv);
MessageBox.Show(messageSendFromClient);
}
}
The error happens @ int recv = server.ReceiveFrom(data, ref remoteEP);
错误发生在@ int recv = server.ReceiveFrom(data, ref remoteEP);
I just need to listen for new incoming connections and then print the message that was sent from the new client. 我只需要侦听新的传入连接,然后打印从新客户端发送的消息。
I need it to work on the TCP protocol, because some of the messages will be > 1500 bytes 我需要它在TCP协议上工作,因为某些消息将大于1500字节
Thanks! 谢谢!
You need to .BeginAccept() before you can receive. 您需要先接收.BeginAccept()才能接收。
Here's a link with a sinple Asynchronous Socket Server example 这是一个带有单一异步套接字服务器示例的链接
ReceiveFrom()适用于UDP,使用Accept()和Receive()适用于TCP
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.