2015-06-07 158 views
0

我写了一个服务器在java和android的客户端,但我无法使用我的android代码找到服务器。无法连接到服务器(从android模拟器到java服务器)

注1:我在java中使用完全相同的代码,并且我可以轻松连接到服务器。注意2:我使用了“10.0.2.2”和“我的电脑IP”,如在Stackoverflow中的某些线程中提到的,但它们都不起作用。

注3:我采用了android工作室

我将不胜感激,如果有人可以帮助我这一点。

他我把里面的onCreate:

cl1 = new Client("192.168.189.1"); 

cl1.startRunning(); 

这是我的客户端类:为了创建一个使用任何连接 :

package com.example.tavoes; 

import java.io.*; 
import java.net.*; 
import java.util.Scanner; 

import android.util.Log; 

public class Client { 


private ObjectOutputStream output; 
private String message = ""; 
private String serverIp; 
private Socket connection; 
private Scanner scanner; 

// constructor 
public Client(String host) { 
super(); 
serverIp = host; 
} 

// connect to server 
public void startRunning() { 

try { 
    connectToServer();    
    setupStream(); 
    whileChatting(); 
} catch (EOFException eofException) { 
    eofException.printStackTrace(); 
} catch (IOException ioException) { 
    ioException.printStackTrace(); 
} /*finally { 
    closeChat(); 
}*/ 
} 

// connect to server 
private void connectToServer() { 

try { 
    connection = new Socket(InetAddress.getByName(serverIp), 4444); 
} catch (IOException e) { 
    e.printStackTrace(); 
    } 
} 

// setup streams to send and receive messages 
private void setupStream() throws IOException { 
output = new ObjectOutputStream(connection.getOutputStream()); 
output.flush(); 
//input = new ObjectInputStream(connection.getInputStream()); 
//System.out.println("Inside Streams are setup!"); 
} 

// While chatting with server 
private void whileChatting() throws IOException { 
//do { 
//output.flush(); 

output.writeObject("<Request connection \"1\" />"); 

scanner=new Scanner(connection.getInputStream()); 
message = scanner.nextLine(); 
//System.out.println(message); 
//message = (String) input.readObject(); 
} 

// close the streams and sockets 
private void closeChat() { 
try { 
    output.close(); 
    //input.close(); 
    connection.close(); 
    //System.out.println("Closing connection"); 
} catch (IOException ioException) { 
    ioException.printStackTrace(); 
} 
} 
} 
+0

你允许从应用程序的网络连接?你在真实设备上试过了吗? –

+0

您需要显示一些相关的代码。 –

+0

我把代码放在第一个andswer – mps

回答

0

只是为了将其标记为解决以备将来参考您需要的网络

  1. 允许应用程序使用网络通过包括permision 到清单

  2. 是否所有网络活动在一个单独的线程 比主线程,或者使用的AsyncTask

相关问题