Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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
0
Question by ms3001 · Jul 02, 2017 at 07:26 AM · androidnetworkingserverclienttcpclient

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

I'm trying to make a simple application which uses TCP to send a few strings from a client application (Android phone) to a server application (Macintosh). I uses two scenes, one for each of the applications.

I tested this functionality by building the client and running it after I clicked the 'Play' button in the unity editor for the server, and it worked, I was able to send the desired strings from one application to the other. The next step was to build the client application for android and use it on an android device while running the server in the Unity editor as done before, changing the IP address from local host to my laptop's IP address. Both devices were connected to the same wifi network. When I did this, I would get this message in my android studio monitor:

Socket error: Connection refused UnityEngine.DebugLogHandler:Internal_Log(LogType, String, Object) UnityEngine.DebugLogHandler:LogFormat(LogType, Object, String, Object[]) UnityEngine.Logger:Log(LogType, Object) UnityEngine.Debug:Log(Object) SendPic:connectToServer() (at...)

Here is the code for the client: using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Net.Sockets; using UnityEngine;

 public class SendPic : MonoBehaviour {
 
     private bool connected = false;
     private TcpClient socket;
     private NetworkStream stream;
     private StreamWriter writer;
     private StreamReader reader;
     public string IP = "localhost";
     public int port = 8888;
     private int count = 0;
 
     public void connectToServer()
     {
         if (connected)    //already connected
             return;
 
         try
         {
             socket = new TcpClient(IP,port);
             stream = socket.GetStream ();
             writer = new StreamWriter (stream);
             reader = new StreamReader (stream);
             connected = true;
             Debug.Log("Connected to: " + IP + ":" + port.ToString());
         }
         catch (Exception e)
         {
             Debug.Log ("Socket error: " + e.Message);
         }
     }
 
     private void Send()
     {
         String Data = Time.time.ToString();
         if (!connected)
             return;
         writer.WriteLine (Data);
         writer.Flush ();
         count = count + 1;
     }
 
     void Start ()
     {
         Invoke ("connectToServer", 1.0f);
         InvokeRepeating ("Send", 0.0f, 0.5f);
     }
 
     void Update () 
     {
         if (count >= 20)
             CancelInvoke ();
     }
 }

Here is the server code:

 using System;
 using System.Collections;
 using System.Collections.Generic;
 using System.IO;
 using System.Net;
 using System.Net.Sockets;
 using UnityEngine;
 
 
 public class ReceivePic : MonoBehaviour 
 {
     public int port = 8888;
     private List<ServerClient> clients;
     private List<ServerClient> disconnects;
     private TcpListener server;
     private bool started = false;
 
     private void Start()
     {
         clients = new List<ServerClient> ();
         disconnects = new List<ServerClient> ();
 
         try
         {
             server = new TcpListener(IPAddress.Any, port);
             server.Start();
 
             StartListening();
             started = true;
             Debug.Log("Server started on port: " + port.ToString());
         }
         catch (Exception e)
         {
             Debug.Log("Socket error: " + e.Message);
         }
     }
 
     private void StartListening() 
     {
         server.BeginAcceptTcpClient (AcceptTcpClient, server);
     }
 
     private void AcceptTcpClient(IAsyncResult ar) 
     {
         TcpListener listener = (TcpListener)ar.AsyncState;
         clients.Add (new ServerClient (listener.EndAcceptTcpClient (ar)));
         Debug.Log("New connection established");
         StartListening ();
     }
 
     private bool isConnected(TcpClient c)
     {
         try 
         {
             if(c != null && c.Client != null && c.Client.Connected)
                 return true;
             else
                 return false;
         }
         catch
         {
             return false; //not able to reach client
         }
 
     }
 
     private void onIncomingData(ServerClient c, string data)
     {
         Debug.Log (c.clientName + "Has sent the following message: " + data);
     }
 
 
     private void Update()
     {
         if (!started)
             return;
         
         foreach (ServerClient c in clients)
         {
             //is the client still connected
             if (!isConnected (c.tcp))
             {
                 c.tcp.Close ();
                 disconnects.Add (c);
                 continue;
             }
 
             //check for message
             NetworkStream s = c.tcp.GetStream();
             if (s.DataAvailable)
             {
                 StreamReader reader = new StreamReader (s, true);
                 string data = reader.ReadLine ();
 
                 if (data != null)
                     onIncomingData (c, data);
             }
         }
     }
 }
 
 public class ServerClient
 {
     public TcpClient tcp;
     public string clientName;
 
     public ServerClient(TcpClient clientSocket) 
     {
         clientName = "Guest";
         tcp = clientSocket;
     }
 }
 

I made that in player settings for the android client, internet access is required.

I'm fairly new to networking so I'm hoping that there might be a simple fix that I can use. I've reproduced this problem on my school wifi network and through a mobile hotspot using a separate phone.

Comment
Add comment
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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by Bunny83 · Jul 02, 2017 at 11:24 AM

Well "Connection refused" sound a lot like you have a firewall setup which might be blocking the connection. So check your laptop's OS setting. It's also possible that your wifi is actively filtering / blocking any traffic that is not authorized. This is common for school networks.

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.

Follow this Question

Answers Answers and Comments

156 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

Related Questions

Using smartphone as controller. How do I send/receive button states? 0 Answers

Unity networking tutorial? 6 Answers

WebGL set up server to receive messages from android app 0 Answers

Network Connection Works Locally, but not Publicly 0 Answers

Network RCP between client server projects 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges