Sending code:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System;
public class TCPClient : MonoBehaviour
{
private Socket socket = null;
private IPEndPoint endPoint = null;
public string ip;
public int port;
string imagename = "1.jpg";
// Use this for initialization
void Start()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
socket.Connect(endPoint);
}
public void SendMegEvent()
{
SendImage(imagename);
}
void SendImage(string fileName)
{
FileStream fs = new FileStream(Application.streamingAssetsPath + "/" + fileName, FileMode.OpenOrCreate, FileAccess.Read);
BinaryReader strread = new BinaryReader(fs);
byte[] bt = new byte[fs.Length];
strread.Read(bt, 0, bt.Length - 1);
socket.Send(bt);
fs.Close();
socket.Close();
}
}
Receiver code:
using UnityEngine;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System;
public class TCPServer : MonoBehaviour
{
private Socket m_socket = null;
private IPEndPoint m_ipEp = null;
private Thread m_thread = null;
private bool isRunningThread = false;
private Queue<byte[]> m_queue;
public string ip;
public int port;
// Use this for initialization
void Start()
{
m_queue = new Queue<byte[]>();
m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_ipEp = new IPEndPoint(IPAddress.Parse(ip), port);
m_socket.Bind(m_ipEp);
m_socket.Listen(5);
isRunningThread = true;
m_thread = new Thread(ReciveMeg);
m_thread.Start();
}
void Update()
{
if (m_queue.Count > 0)
{
byte[] temp = m_queue.Dequeue();
FileStream fs = File.Create(Application.streamingAssetsPath + "/" + "1.jpg");
fs.Write(temp, 0, temp.Length);
fs.Close();
}
}
void ReciveMeg()
{
while (isRunningThread)
{
Socket socket = m_socket.Accept();
byte[] buffer = new byte[2000000];
socket.Receive(buffer, buffer.Length, SocketFlags.None);
m_queue.Enqueue(buffer);
socket.Close();
}
}
}