【发布时间】:2019-08-22 10:29:51
【问题描述】:
我正在尝试在我的移动设备和桌面之间建立套接字连接。移动设备(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 上的服务器。我怎样才能解决这个问题?
【问题讨论】:
-
安卓和桌面一样吗?是android“192.168.122.24”的IP?
-
如果您没有收到异常,请首先检查您的网络连接是否正常。您可以从任一设备 ping 通这些端口吗?
-
是的,它是同一个wifi,ip当然是192.168.122.24
-
您在尝试连接时是否遇到任何错误/异常?
-
我尝试 ping 并且我能够 ping 它
标签: c# unity3d tcpclient tcplistener android-unity-plugin