Android应用程序和Java服务器的问题。拒绝连接 [英] Android Application and Java server issue. Connection refused

查看:116
本文介绍了Android应用程序和Java服务器的问题。拒绝连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我的Andr​​oid应用程序的问题,应连接到Java的TCP服务器。我收到连接被拒绝的错误。

I have a problem with my android application which should connect to java tcp server. I'm getting Connection refused error.

server.java

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

从客户端

片段在Android:

snippet from client on android:

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

程序正试图在本地主机连接端口6789

program is trying to connect on localhost on port 6789

推荐答案

本地主机这不是你的PC / MAC /无论你使用的计算机的IP或IP专用的http://developer.android.com/guide/developing/devices/emulator.html#networkaddresses

"localhost" it's not your pc/mac/whatever use you pc ip or special ip http://developer.android.com/guide/developing/devices/emulator.html#networkaddresses

这篇关于Android应用程序和Java服务器的问题。拒绝连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆