我有两个项目,一个Java 服务器和一个用C#编写的统一客户端。当我运行java服务器时,Unity应用程序已在Windows上成功连接。但是,当我尝试连接真正的Android设备时,它无法正常工作.Android使用USB线连接到笔记本电脑。
简单的java代码
package main;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class Server1 {
private static final int portnumber=6422;
public static void main(String[] args){
ServerSocket serverSocket =null;
try {
System.out.println("Server starts on port"+portnumber);
serverSocket = new ServerSocket(portnumber);
//Client connecting
System.out.println("Waiting for clients to connect");
Socket socket = serverSocket.accept();
System.out.println("A client has connected");
System.out.println("server has ended");
}catch (IOException e){
e.printStackTrace();
}
}
}
客户代码
using UnityEngine;
using System.Net.Sockets;
using System.IO;
using System;
public class Client : MonoBehaviour
{
private bool socketready;
private TcpClient socket;
public void ConnectToServer()
{
//if already connected , ignore this function
if (socketready)
return;
//my laptop private ip address.
string host = "192.168.1.2";
int port = 6422;
//create the socket
try
{
socket = new TcpClient(host, port);
socketready = true;
}
catch (Exception e)
{
print("socket error: " + e.Message);
}
}}
在统一中我有按钮(将调用ConnectToServer
)。问题是当我尝试点击此按钮时无法在 java控制台中获得“客户端已连接”。
在android studio上,它显示“socket error: Connection timed out
”