- Home /
how can i send image or texture and text through TCP to send data from mobile to pc
now am working on a project need to send photo and feed back from mobile to pc in pc these info will be displayed in my case i use tcp for networking i can send recive text but the send texture 2d of image is not working
using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine; using UnityEngine.UI;
public class TCPTestServer : MonoBehaviour {
private TcpListener tcpListener; private Thread tcpListenerThread;
private TcpClient connectedTcpClient; private bool stop = false;
//server
public string IP;
public Text Outputext;
public int size;
Texture2D tex;
public RawImage Image;
public Text IPtext;
//This must be the-same with SEND_COUNT on the client
const int SEND_RECEIVE_COUNT = 15;
// Use this for initialization
void Start () {
// Start TcpServer background thread
LocalIPAddress();
tcpListenerThread = new Thread (new ThreadStart(ListenForIncommingRequests));
tcpListenerThread.IsBackground = true;
tcpListenerThread.Start();
IPtext.text = IP;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space)) {
SendMessage();
}
}
public string LocalIPAddress()
{
IPHostEntry host;
IP = "";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
IP = ip.ToString();
break;
}
}
return IP;
}
/// <summary>
/// Runs in background TcpServerThread; Handles incomming TcpClient requests
/// </summary>
private void ListenForIncommingRequests () {
try {
// Create listener on localhost port 8052.
tcpListener = new TcpListener(IPAddress.Parse(IP), 8052);
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] bytes = new Byte[1024];
while (true) {
using (connectedTcpClient = tcpListener.AcceptTcpClient()) {
// Get a stream object for reading
using (NetworkStream stream = connectedTcpClient.GetStream()) {
int length;
size = SEND_RECEIVE_COUNT;
bool disconnected = false;
// Read incomming stream into byte arrary.
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0) {
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length);
// Convert byte array to string message.
string clientMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("client message received as: " + clientMessage);
Outputext.text = clientMessage;
}
byte[] imageBytes = new byte[size];
var total = 0;
do
{
var read = stream.Read(imageBytes, total, size - total);
//Debug.LogFormat("Client recieved {0} bytes", total);
if (read == 0)
{
disconnected = true;
break;
}
total += read;
} while (total != size);
bool readyToReadAgain = false;
//Display Image
if (!disconnected)
{
//Display Image on the main Thread
Loom.QueueOnMainThread(() =>
{
displayReceivedImage(imageBytes);
readyToReadAgain = true;
});
}
//Wait until old Image is displayed
while (!readyToReadAgain)
{
System.Threading.Thread.Sleep(1);
}
}
}
}
}
catch (SocketException socketException) {
Debug.Log("SocketException " + socketException.ToString());
}
}
void displayReceivedImage(byte[] receivedImageBytes)
{
tex.LoadImage(receivedImageBytes);
Image.texture = tex;
}
/// <summary>
/// Send message to client using socket connection.
/// </summary>
private void SendMessage() {
if (connectedTcpClient == null) {
return;
}
try {
// Get a stream object for writing.
NetworkStream stream = connectedTcpClient.GetStream();
if (stream.CanWrite) {
string serverMessage = "This is a message from your server.";
// Convert string message to byte array.
byte[] serverMessageAsByteArray = Encoding.ASCII.GetBytes(serverMessage);
// Write byte array to socketConnection stream.
stream.Write(serverMessageAsByteArray, 0, serverMessageAsByteArray.Length);
Debug.Log("Server sent his message - should be received by client");
}
}
catch (SocketException socketException) {
Debug.Log("Socket exception: " + socketException);
}
}
}
//Clint using System; using System.Collections; using System.Collections.Generic; using System.Net.Sockets; using System.Text; using System.Threading; using UnityEngine; using System.Net; using UnityEngine.UI;
public class TCPTestClient : MonoBehaviour { #region private members
private TcpClient socketConnection; private Thread clientReceiveThread; #endregion //clint public InputField IpInput; public string IP; public Texture2D InputTexture; Texture2D Currenttexture;
//This must be the-same with SEND_COUNT on the client
const int SEND_RECEIVE_COUNT = 15;
// Use this for initialization
void Start()
{
IpInput.text = IP;
ConnectToTcpServer();
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
SendMessage();
}
}
/// <summary>
/// Setup socket connection.
/// </summary>
public void ConnectToTcpServer()
{
try
{
clientReceiveThread = new Thread(new ThreadStart(ListenForData));
clientReceiveThread.IsBackground = true;
clientReceiveThread.Start();
}
catch (Exception e)
{
Debug.Log("On client connect exception " + e);
}
}
/// <summary>
/// Runs in background clientReceiveThread; Listens for incomming data.
/// </summary>
private void ListenForData()
{
try
{
IP = IpInput.text;
IPEndPoint iPEnd = new IPEndPoint(IPAddress.Parse(IP), 8052);
socketConnection = new TcpClient();
socketConnection.Connect(iPEnd);
Byte[] bytes = new Byte[1024];
while (true)
{
// Get a stream object for reading
using (NetworkStream stream = socketConnection.GetStream())
{
int length;
// Read incomming stream into byte arrary.
while ((length = stream.Read(bytes, 0, bytes.Length)) != 0)
{
var incommingData = new byte[length];
Array.Copy(bytes, 0, incommingData, 0, length);
// Convert byte array to string message.
string serverMessage = Encoding.ASCII.GetString(incommingData);
Debug.Log("server message received as: " + serverMessage);
}
}
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
}
/// <summary>
/// Send message to server using socket connection.
/// </summary>
private void SendMessage()
{
if (socketConnection == null)
{
return;
}
try
{
// Get a stream object for writing.
NetworkStream stream = socketConnection.GetStream();
if (stream.CanWrite)
{
string clientMessage = "This is a message from one of your clients.";
// Convert string message to byte array.
byte[] clientMessageAsByteArray = Encoding.ASCII.GetBytes(clientMessage);
// Write byte array to socketConnection stream.
stream.Write(clientMessageAsByteArray, 0, clientMessageAsByteArray.Length);
Debug.Log("Client sent his message - should be received by server");
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
}
public void SendImage()
{
if (socketConnection == null)
{
return;
}
try
{
// Get a stream object for writing.
NetworkStream stream = socketConnection.GetStream();
if (stream.CanWrite)
{
bool readyToGetFrame = true;
byte[] frameBytesLength = new byte[SEND_RECEIVE_COUNT];
//Wait for End of frame
//yield return endOfFrame;
Currenttexture = new Texture2D(InputTexture.width, InputTexture.height);
Currenttexture.SetPixels(InputTexture.GetPixels());
byte[] pngBytes = Currenttexture.EncodeToPNG();
//Fill total byte length to send. Result is stored in frameBytesLength
byteLengthToFrameByteArray(pngBytes.Length, frameBytesLength);
//Set readyToGetFrame false
readyToGetFrame = false;
Loom.RunAsync(() =>
{
//Send total byte count first
stream.Write(frameBytesLength, 0, frameBytesLength.Length);
//LOG("Sent Image byte Length: " + frameBytesLength.Length);
//Send the image bytes
stream.Write(pngBytes, 0, pngBytes.Length);
//LOG("Sending Image byte array data : " + pngBytes.Length);
//Sent. Set readyToGetFrame true
readyToGetFrame = true;
});
}
}
catch (SocketException socketException)
{
Debug.Log("Socket exception: " + socketException);
}
}
void byteLengthToFrameByteArray(int byteLength, byte[] fullBytes)
{
//Clear old data
Array.Clear(fullBytes, 0, fullBytes.Length);
//Convert int to bytes
byte[] bytesToSendCount = BitConverter.GetBytes(byteLength);
//Copy result to fullBytes
bytesToSendCount.CopyTo(fullBytes, 0);
}
}
Please use an editor to invent your whole code by 5+ spaces to fix your question display issues
Answer by thelghome · Dec 01, 2019 at 03:58 PM
We have complete solution for Streaming Game View, Images, string msg, and byte[] via UDP/WebSocket/TCP, with FMETP STREAM
Asset Store: http://u3d.as/1uHj
Your answer
Follow this Question
Related Questions
Unity networking tutorial? 6 Answers
Unity tcp_client only working on localhost 1 Answer
Unity TCP async functions 0 Answers
Problems with TLS handshake 0 Answers