zoukankan      html  css  js  c++  java
  • socket.BeginReceiveFrom异步接收信息时,回调函数无法正常进入

    Server:

    using System;
    using System.Net;
    using System.Net.Sockets;
    public class UdpServer
    {
    static Socket serverSock;
    static AsyncCallback receiveCallback;
    static byte[] buff;
    static EndPoint senderIP ;

    public static void Main()
    {
    buff = new byte[1024];
    senderIP = new IPEndPoint(IPAddress.Any, 0);

    receiveCallback = new AsyncCallback(OnDataReceived);

    serverSock = new Socket(AddressFamily.InterNetwork,
    SocketType.Dgram, ProtocolType.Udp);
    serverSock.Bind(new IPEndPoint(IPAddress.Any, 8000));


    serverSock.BeginReceiveFrom(buff, 0, buff.Length, SocketFlags.None,
    ref senderIP, receiveCallback, serverSock);

    Console.ReadLine();

    }

    public static void OnDataReceived(IAsyncResult ar)
    {
    Socket udpSocket = ar.AsyncState as Socket;
    int bytesRecved = udpSocket.EndReceiveFrom(ar, ref (EndPoint)senderIP);

    Console.WriteLine("{0}传来消息{1}", senderIP.ToString(), System.Text.Encoding.ASCII.GetString(buff, 0, bytesRecved));

    serverSock.BeginReceiveFrom(buff, 0, buff.Length, SocketFlags.None,
    ref senderIP, receiveCallback, serverSock);
    }
    }

    Client:

    using System;
    using System.Net;
    using System.Net.Sockets;
    public class UdpClient
    {
    static Socket clientSock;
    static byte[] buff;

    public static void Main()
    {
    clientSock = new Socket(AddressFamily.InterNetwork,
    SocketType.Dgram, ProtocolType.Udp);

    string input;
    while((input = Console.ReadLine()) != "exit")
    {
    buff = System.Text.Encoding.ASCII.GetBytes(input);
    clientSock.SendTo(buff, 0, buff.Length, SocketFlags.None, new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8000));
    }

    clientSock.Close();
    }
    }




  • 相关阅读:
    ORB_SLAM2 源码阅读 ORB_SLAM2::ORBextractor
    macOS 安装 pcl 1.8.0
    [LeetCode] #112 #113 #437 Path Sum Series
    Mybatis之Plus
    Spring实战经验
    linux命令汇总
    跨域问题
    Python之mqtt接收异步消息
    Python之IO模块
    python多线程库之threading
  • 原文地址:https://www.cnblogs.com/graypigeon/p/2373824.html
Copyright © 2011-2022 走看看