c#的udp通讯代码

来源:互联网 发布:淘宝号登录 编辑:程序博客网 时间:2024/05/18 11:28

//Author:smilelance

//From:http://blog.csdn.net/smilelance


using UnityEngine;

using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;


public class UdpConnection {
private static UdpConnection instance;
private const System.Int32 serverPort = 8320;
private const string serverAddress = "10.1.13.157";
UdpClient udpClient;

    private UdpConnection()
{
    
    }


    public static UdpConnection GetInstance()
    {
      if(instance==null){
        instance=new UdpConnection();
        }
        return instance;
    }

public void startUdpConnection(){
udpClient = new UdpClient();
        udpClient.Connect(serverAddress, serverPort);

//IPEndPoint object will allow us to read datagrams sent from any source.
        IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);


         // Sends a message to the host to which you have connected.
         byte[] sendBytes = Encoding.UTF8.GetBytes("Client start online?");
// AsyncSend(sendBytes);
         //udpClient.Send(sendBytes, sendBytes.Length);
 
AsyncReceive();
}

// 发送数据 
public void AsyncSend(byte[] data){
        if (data.Length > 0){
// Debug.Log("sending : " + Encoding.UTF8.GetString(data));
           //udpClient.Send(data, data.Length, ipep);
udpClient.BeginSend(data, data.Length, new AsyncCallback(SendDataCallback), null);
}
}

//接收数据
public void AsyncReceive(){
        udpClient.BeginReceive(new AsyncCallback(ReceiveDataCallback), null);
}

//发送数据callback
public static bool messageSent = false;

private void SendDataCallback(IAsyncResult ar)
{
  //UdpClient u = (UdpClient)ar.AsyncState;
//print(u.EndSend(ar));
//u.EndSend(ar);
// Debug.Log("sending successfule");
  messageSent = true;
}



    //接收数据callback
    private void ReceiveDataCallback(IAsyncResult ar)
    {
        IPEndPoint ipep = (IPEndPoint)ar.AsyncState;
        byte[] data = udpClient.EndReceive(ar, ref ipep);
        if (data.Length != 0){
//            OnReceiveData(new UdpSimpleEventArgs(ipep, data));
// string returnData = Encoding.UTF8.GetString(data);
// Debug.Log("recv data: " + returnData);
MessageReceiver.GetInstance().parseReseiveMsg(data);
}
        //继续从远程主机接收数据报
        AsyncReceive();
    }
}