- Home /
I have a problem in Android socket comm with PC
Hello, Unity guys (?) I am a student who wants to study UNITY for the experiment
Anyway, I'm developing UNITY module for HID (Human Interface Device) by using socket Comm
In detail, build server in UNITY system and make a client which gets data from the external device and transfer preprocessed data to UNITY server.
And all was well before my program run on Android and the problem comes up after that
In the PC environment, my program works very well by using localhost but when I try to connect to PC in Android app, they can not find each other both server and client. Be frankly, I can't explain this problem better than this, sorry I attach my source code
I'm wondering if I need to add source code for use in the Android environment or for connecting to the external socket.
Thank you for reading me
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
public class Player : MonoBehaviour {
static Socket server;
Socket accpeted;
static byte[] buffer { get; set; }
bool isStarted = false;
string strdata;
// Use this for initialization
void Start () {
Application.runInBackground = true;
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.Bind(new IPEndPoint(IPAddress.Any, 23000));
Thread data_th = new Thread(receiveData);
data_th.Start();
}
// Update is called once per frame
void Update () {
if (isStarted)
{
goSpeed(1, strdata);
}
}
void receiveData()
{
while (true)
{
try
{
if (isStarted)
{
int bytesRead = accpeted.Receive(buffer);
byte[] formatted = new byte[bytesRead];
for (int i = 0; i < bytesRead; i++)
{
formatted[i] = buffer[i];
}
strdata = Encoding.UTF8.GetString(formatted);
Debug.Log("Get " + strdata + "\r\n");
}
else
{
server.Listen(100);
accpeted = server.Accept();
buffer = new byte[accpeted.SendBufferSize];
isStarted = true;
}
}
catch { }
Thread.Sleep(250);
}
}
void goSpeed(float velocity ,string direction) // FB : X , LR : Z
{
float speed = velocity * Time.deltaTime;
if (direction == "GF") transform.Translate(Vector3.forward * speed);
else if (direction == "GB") transform.Translate(Vector3.back * speed);
else if (direction == "GL") transform.Translate(Vector3.left * speed);
else if (direction == "GR") transform.Translate(Vector3.right * speed);
else if (direction == "TR") transform.Rotate(Vector3.right);
else if (direction == "TL") transform.Rotate(Vector3.left);
}
}