我正在尝试在我的移动设备和桌面之间建立套接字连接。移动设备(Android)将充当服务器,而桌面是客户端机器。
以下是我的服务器代码,
public class PhoneCamera : MonoBehaviour
{
private TcpListener listner;
private const int port = 8010;
private bool stop = false;
private List<TcpClient> clients = new List<TcpClient>();
public void Start ()
{
Application.runInBackground = true;
initAndWaitForWebCamTexture();
}
void initAndWaitForWebCamTexture()
{
listner = new TcpListener(IPAddress.Any, port);
listner.Start();
//Start sending coroutine
StartCoroutine(senderCOR());
}
WaitForEndOfFrame endOfFrame = new WaitForEndOfFrame();
IEnumerator senderCOR()
{
bool isConnected = false;
TcpClient client = null;
NetworkStream stream = null;
// Wait for client to connect in another Thread
Loom.RunAsync(() =>
{
while (!stop)
{
// Wait for client connection
client = listner.AcceptTcpClient();
// We are connected
clients.Add(client);
isConnected = true;
stream = client.GetStream();
}
});
//Wait until client has connected
while (!isConnected)
{
yield return null;
}
LOG("Connected!");
}
void LOG(string messsage)
{
Debug.Log(messsage);
}
private void Update ()
{
}
}
以下是客户端的代码
public class Receiver : MonoBehaviour
{
public bool enableLog = false;
const int port = 8010;
public string IP = "192.168.122.24";
TcpClient client;
private bool stop = false;
//This must be the-same with SEND_COUNT on the server
const int SEND_RECEIVE_COUNT = 15;
// Use this for initialization
void Start()
{
Application.runInBackground = true;
tex = new Texture2D(0, 0);
client = new TcpClient();
//Connect to server from another Thread
Loom.RunAsync(() =>
{
LOGWARNING("Connecting to server...");
// if on desktop
client.Connect(IPAddress.Loopback, port);
// if using the IPAD
//client.Connect(IPAddress.Parse(IP), port);
Debug.Log("Connected");
});
}
void Update()
{
}
void OnApplicationQuit()
{
LOGWARNING("OnApplicationQuit");
stop = true;
if (client != null)
{
client.Close();
}
}
}
但由于某种原因,客户端不会连接到运行在 Android 上的服务器。我怎样才能解决这个问题?