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();
    }
    }




  • 相关阅读:
    Duff and Meat(贪心)
    Duff and Meat(贪心)
    Eugeny and Array(水题,注意题目描述即可)
    Eugeny and Array(水题,注意题目描述即可)
    HDU-2588-GCD (欧拉函数)
    HDU-2588-GCD (欧拉函数)
    再谈欧拉函数
    再谈欧拉函数
    容斥定理及浅略介绍
    Vue
  • 原文地址:https://www.cnblogs.com/graypigeon/p/2373824.html
Copyright © 2011-2022 走看看