Skip to content

Instantly share code, notes, and snippets.

@mortennobel
Last active May 9, 2016 20:35
Show Gist options
  • Save mortennobel/eb3ef3773ce3baf9789a6747f63bae2c to your computer and use it in GitHub Desktop.
Save mortennobel/eb3ef3773ce3baf9789a6747f63bae2c to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class HelloSocketWorld : MonoBehaviour {
public string history;
public string txt;
private byte[] _recieveBuffer = new byte[8142];
// Use this for initialization
void Start () {
clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Loopback,port));
clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new System.AsyncCallback(ReceiveCallback),null);
history = history + "\nServer Connected ...";
}
private void ReceiveCallback(System.IAsyncResult AR){
//Check how much bytes are recieved and call EndRecieve to finalize handshake
int recieved = clientSocket.EndReceive(AR);
if(recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
System.Buffer.BlockCopy(_recieveBuffer,0,recData,0,recieved);
//Process data here the way you want , all your bytes will be stored in recData
var dataFromClient = System.Text.Encoding.ASCII.GetString(
recData, 0, recData.Length);
history += dataFromClient;
//Start receiving again
clientSocket.BeginReceive(_recieveBuffer,0,_recieveBuffer.Length,SocketFlags.None,new System.AsyncCallback(ReceiveCallback),null);
}
// Update is called once per frame
void Update () {
}
// The port number for the remote device.
private const int port = 5000;
private Socket clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
NetworkStream serverStream;
private void SendData(byte[] data)
{
SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
socketAsyncData.SetBuffer(data,0,data.Length);
clientSocket.SendAsync(socketAsyncData);
}
void OnGUI(){
history = GUI.TextField (new Rect (0, 0, 200, 300), history);
txt = GUI.TextField (new Rect (0, 300, 200, 50), txt);
if (GUI.Button(new Rect(0,350,0200,50),"Send")){
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txt);
SendData (outStream);
history += "\nMe: " + txt;
txt = "";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment