日期:2014-05-18  浏览次数:20722 次

c#的udp通讯代码

//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)
{
  /