Skip to content

Instantly share code, notes, and snippets.

@William-ST
Created May 29, 2017 04:45
Show Gist options
  • Save William-ST/2259c8fb999917bfe67216c8258cb571 to your computer and use it in GitHub Desktop.
Save William-ST/2259c8fb999917bfe67216c8258cb571 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 SocketConnection : MonoBehaviour {
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private byte[] _recieveBuffer = new byte[8142];
void Start()
{
Debug.Log("onStart");
SetupServer();
}
private void SetupServer()
{
Debug.Log("SetupServer");
try
{
_clientSocket.Connect(new IPEndPoint(System.Net.IPAddress.Parse("127.0.0.1")/*IPAddress.Loopback*/, 3000));
}
catch (SocketException ex)
{
Debug.Log(ex.Message);
}
/*
Debug.Log("-- 1");
Debug.Log("socket connect? -> " + _clientSocket.Connected);
Debug.Log("-- 2");
SendData(System.Text.Encoding.UTF8.GetBytes("Campi"));
Debug.Log("-- 3");
*/
//SendData(Encoding.ASCII.GetBytes("connection"));
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
}
private void ReceiveCallback(IAsyncResult AR)
{
Debug.Log("ReceiveCallback");
//Check how much bytes are recieved and call EndRecieve to finalize handshake
int recieved = _clientSocket.EndReceive(AR);
Debug.Log("ReceiveCallback 1 recieved: " + recieved);
if (recieved <= 0)
return;
//Copy the recieved data into new buffer , to avoid null bytes
byte[] recData = new byte[recieved];
Buffer.BlockCopy(_recieveBuffer, 0, recData, 0, recieved);
Debug.Log("ReceiveCallback 2: " + recData.Length+" - "+recData.ToString());
Debug.Log("ReceiveCallback 3: " + Encoding.ASCII.GetString(recData)+" : ");
Debug.Log("ReceiveCallback 4");
//Process data here the way you want , all your bytes will be stored in recData
//Start receiving again
_clientSocket.BeginReceive(_recieveBuffer, 0, _recieveBuffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);
Debug.Log("ReceiveCallback 5");
}
private void SendData(byte[] data)
{
SocketAsyncEventArgs socketAsyncData = new SocketAsyncEventArgs();
socketAsyncData.SetBuffer(data, 0, data.Length);
_clientSocket.SendAsync(socketAsyncData);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment