Skip to content

Instantly share code, notes, and snippets.

@diegodorado
Last active October 3, 2020 01:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save diegodorado/9e8d9a484185ed43d6ea86b1e7a876fa to your computer and use it in GitHub Desktop.
Save diegodorado/9e8d9a484185ed43d6ea86b1e7a876fa to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class UDPClient : MonoBehaviour
{
public byte[] buffer = new byte[bufSize];
private Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int bufSize = 256;
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
void Awake()
{
InitClient("127.0.0.1", 9034);
}
void InitClient(string address, int port)
{
socket.Connect(IPAddress.Parse(address), port);
socket.BeginReceiveFrom(buffer, 0, bufSize, SocketFlags.None, ref epFrom, ReceiveHandler,buffer);
}
private void ReceiveHandler(IAsyncResult ar)
{
int bytes = socket.EndReceiveFrom(ar, ref epFrom);
socket.BeginReceiveFrom(buffer, 0, bufSize, SocketFlags.None, ref epFrom, ReceiveHandler, buffer);
Debug.LogFormat("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, Encoding.ASCII.GetString(buffer, 0, bytes));
}
public void Send(string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
int bytes = socket.EndSend(ar);
Debug.LogFormat("SEND: {0}, {1}", bytes, text);
}, buffer);
}
public void SendFromUI(UnityEngine.UI.InputField input)
{
Send(input.text);
}
void Update()
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment