无法连接到服务器(从android模拟器到java服务器)

时间:2015-06-07 15:51:45

标签: java android server

我在java中编写了一个服务器,在android中编写了一个客户端,但我无法使用我的android代码找到服务器。

注1:我在java中使用完全相同的代码,我可以轻松连接到服务器。

注2:我使用" 10.0.2.2"还有我的电脑ip"正如Stackoverflow中的一些线程中所提到的,但它们都没有工作。

注3:我正在使用android studio

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

他把我放进了创作:

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();
}
}
}

1 个答案:

答案 0 :(得分:0)

只是将其标记为已解决以供将来参考: 为了使用您需要的网络创建任何连接

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

  2. 在单独的线程上执行所有网络活动 比主线程,或使用AsyncTask

相关问题