Last active
October 3, 2020 01:33
-
-
Save diegodorado/9e8d9a484185ed43d6ea86b1e7a876fa to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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