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




  • 相关阅读:
    enum
    高可用复用类
    int 和 Integer 的区别
    MysqlMd5加密
    软件测试例子
    Wordcount
    大气登录页面
    生成二维码的JAVA
    多态的理解
    打印低头思故乡 java
  • 原文地址:https://www.cnblogs.com/graypigeon/p/2373824.html
Copyright © 2011-2022 走看看