我在Android工作室工作,我试图连接我做的服务器,但没有成功。当我使用这个代码时,我能够在客户端是我的计算机时连接客户端到服务器:
socket = null;
try
{
Log.e("client", "Attempting to connect to serverrrrrr.");
socket = new Socket(hostname, portnumber);
Log.e("client", "Connected ! ");
主机名如下:
private static final String hostname= "localhost";
private static final int portnumber=55555;
然后,我意识到当我尝试从手机连接到客户端时,它无法工作,因为我需要放置一个真正的IP地址,而不是localhost的东西。因此,我尝试了这个:
private static final String hostname= "10.0.0.1";
private static final int portnumber=55555;
使用上面相同的代码,但它不起作用。它只是停留在:新插座...... 它没有前进,因此没有真正的联系。我究竟做错了什么 ?
我也有这段代码:<uses-permission android:name="android.permission.INTERNET"/>
我做了“端口转发”。我还可以做些什么 ?
01-30 18:16:47.760 16158-16210/com.omer.tictactoemultiplayer W/System.err: java.net.ConnectException: failed to connect to /10.0.0.1 (port 55555): connect failed: ETIMEDOUT (Connection timed out)
服务器代码:`public class Server extends Thread {
private static final int portnumber = 55555;
@Override
public void run() {
ServerSocket serverSocket = null;
try {
Log.e("Server", "Server starting at port number: " + portnumber);
serverSocket = new ServerSocket(portnumber);
while(true)
{
// Client connecting.
Log.e("Server", "Waiting for clients to connect ...");
Socket socket1 = serverSocket.accept();
Log.e("Server", "Client one has connected.");
Socket socket2 = serverSocket.accept();
Log.e("Server", "Client two has connected.");
//Send message to the server.1
BufferedWriter bw1 = new BufferedWriter(new OutputStreamWriter(socket1.getOutputStream()));
bw1.write("found");
bw1.newLine();
bw1.flush();
BufferedWriter bw2 = new BufferedWriter(new OutputStreamWriter(socket2.getOutputStream()));
bw2.write("found");
bw2.newLine();
bw2.flush();
new ServerThread(socket1,socket2).start();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
} `
答案 0 :(得分:0)
如果您尝试通过手机连接电脑,则必须进行更改 private static final String hostname =“localhost”for
private static final String hostname = your-pc-ip
你可以在windows中看到ip命令ipconfig,在linux中看到ifconfig
答案 1 :(得分:0)
如果您只将主机从localhost更改为计算机的IP,那么在您的PC上运行得非常好的Java代码将无法用于Android。
那时你必须把互联网代码放在一个线程或AsyncTask中。
如果你不这样做,你会在logcat中清楚地看到NetworkOnMainThreadException
。