• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by vsksanthosh15 · Oct 15, 2019 at 07:02 AM · networkingservertcptcpclient

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);
 }

}

Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image lgarczyn · Oct 16, 2019 at 06:58 AM 0
Share

Please use an editor to invent your whole code by 5+ spaces to fix your question display issues

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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

Forum: https://forum.unity.com/threads/670270/

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

162 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Unity networking tutorial? 6 Answers

TcpClient not working when building, 1 Answer

Unity tcp_client only working on localhost 1 Answer

Unity TCP async functions 0 Answers

TCP Server/Client with Laptop/Phone doesn't work with devices, does work on local host. 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges