【问题标题】:Android Application and Java server issue. Connection refusedAndroid 应用程序和 Java 服务器问题。拒绝连接
【发布时间】:2011-11-09 15:17:59
【问题描述】:

我的 android 应用程序有问题,它应该连接到 java tcp 服务器。我收到连接被拒绝错误。

server.java

public class Server
{
public static void main(String argv[]) throws Exception
{
ServerSocket welcomeSocket = new ServerSocket(6789);
System.out.println("welcome into server");
while(true)
{

Socket connectionSocket = welcomeSocket.accept();
if (connectionSocket != null)
{
System.out.println(connectionSocket);
Client client = new Client(connectionSocket);
client.start();
}
}
}
}

class Client extends Thread

private Socket connectionSocket;
private String clientSentence;
private String ans;
private String temak="test";
private String capitalizedSentence;
private BufferedReader inFromClient;
private DataOutputStream outToClient;

public Client(Socket c) throws IOException
{
connectionSocket = c;
}

public void run() 
{
try
{ 
inFromClient = new BufferedReader(new nputStreamReader(connectionSocket.getInputStream()));
outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
capitalizedSentence = clientSentence.toUpperCase() + '\n';
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
ans = inFromUser.readLine();
outToClient.writeBytes(capitalizedSentence);
if("hej".equals(clientSentence)){
outToClient.writeBytes(ans + " tester hej"+ "\n");
}
else{
outToClient.writeBytes(ans+"\n");
}
}
catch(IOException e)
{
System.out.println("Errore: " + e);
}
}
}

来自安卓客户端的sn-p:

String sentence = null; 
String modifiedSentence; 
String tempus;
try {

Socket clientSocket = new Socket("localhost", 6789);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Log.d("pre","TCP Connected.");

outToServer.writeBytes(sentence + 'n');
modifiedSentence = inFromServer.readLine();
Log.d("sentence ", modifiedSentence);
Log.d("post","TCP Success !!!");

clientSocket.close();

} catch (Exception e) {
Log.d("error","TCP Error: " + e.toString());
}

程序正在尝试连接 localhost 的 6789 端口

【问题讨论】:

  • 您能否编辑您的代码示例以正确进行缩进。现在很难阅读。
  • localhost 是 android 设备而不是你的 PC/Mac/Whatever
  • 那么如何离开设备?输入我的ip?
  • 谢谢塞尔文!!适用于 10.0.2.2!

标签: java android network-programming


【解决方案1】:

"localhost" 这不是你的 pc/mac/无论你使用什么 pc ip 或特殊 ip (10.0.2.2) 更多检查:https://developer.android.com/studio/run/emulator-commandline.html#emulatornetworking

【讨论】:

    【解决方案2】:

    根据例如(编辑:)this Selvin 写的,你应该使用 IP 地址10.0.2.2 连接到运行模拟器的 PC。 (localhost127.0.0.1 从模拟器内循环回模拟器。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多