我想将android上的Unity app与计算机应用程序连接起来。我可以在网络上运行它,但在互联网上它总是说机器拒绝连接。我已禁用Windows防火墙和防病毒软件,但仍然无法连接服务器和Android客户端:
No connection could be made because the target machine actively refused it.
以下是代码:
服务器端:
TcpListener tcpListener;
Socket socket;
NetworkStream networkStream;
Thread thread;
string getIpAddress()
{
System.Net.IPHostEntry host;
string localIp = "";
host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (System.Net.IPAddress ip in host.AddressList)
{
localIp = ip.ToString();
}
return localIp;
}
public void ReceiveImage()
{
try
{
IPAddress localAddr = IPAddress.Parse("95.171.54.53");
tcpListener = new TcpListener(localAddr, 53100);
tcpListener.Start();
socket = tcpListener.AcceptSocket();
networkStream = new NetworkStream(socket);
pictureBox1.Image = Image.FromStream(networkStream);
if (socket.Connected == true)
{
while (true)
{
tcpListener.Stop();
ReceiveImage();
}
}
}
catch(Exception ex)
{
string Message = ex.Message;
}
}
private void Form1_Load(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(ReceiveImage));
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
tcpListener.Stop();
thread.Abort();
}
这是客户方:
// Update is called once per frame
int frameSaveCount = -1;
int FrameCount = -1;
Socket socket;
NetworkStream networkStream;
Thread thread;
MemoryStream memoryStream;
TcpClient tcpClient;
BinaryWriter binaryWriter;
void Update()
{
// ...
if(FrameCount % 10==0)
{
// ...
send(bytes);
}
}
void send(Byte[] bytes)
{
try
{
print(getIpAddress());
tcpClient = new TcpClient("95.171.54.53", 53100);
networkStream = tcpClient.GetStream();
binaryWriter = new BinaryWriter(networkStream);
binaryWriter.Write(bytes);
binaryWriter.Close();
networkStream.Close();
tcpClient.Close();
}
catch (Exception exception)
{
string message = exception.Message;
print(message);
}
}
答案 0 :(得分:1)
机器拒绝连接
此错误只有一个含义:没有任何内容正在侦听您尝试连接的IP:端口。所以,要么是错误的,要么当您的客户端尝试连接时,您的服务器都没有启动。
图像文件与它完全无关。