gpt4 book ai didi

java - Android 应用程序和 Java 服务器问题。连接被拒绝

转载 作者:行者123 更新时间:2023-12-01 19:12:03 25 4
gpt4 key购买 nike

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

服务器.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 客户端的 fragment :

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

最佳答案

“localhost”不是你的电脑/mac/任何使用你的电脑IP或特殊IP(10.0.2.2)更多信息请查看:https://developer.android.com/studio/run/emulator-commandline.html#emulatornetworking

关于java - Android 应用程序和 Java 服务器问题。连接被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8067113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com