gpt4 book ai didi

Java服务器android客户端通过不同网络进行通信

转载 作者:搜寻专家 更新时间:2023-11-01 08:42:05 24 4
gpt4 key购买 nike

我正在实现聊天应用程序,其中服务器是基于 java 的,客户端是 android 的。我的服务器代码是使用套接字编程用 java 语言编写的。当我将我的 android 手机(互联网打开)与笔记本电脑连接并启动服务器和客户端时,它工作正常。在我的客户端应用程序中,我必须输入服务器机器的 IP 地址,例如 192.168..。当客户端向服务器发送消息时,服务器将响应返回给客户端。没关系。

但是当我从不在我的家庭网络中的其他安卓手机运行客户端时(假设我的 friend 在他家并尝试通过互联网连接 java 服务器(在我家))。然后服务器没有显示连接建立.我也尝试在启动时将我的公共(public) IP 地址从谷歌放入客户端应用程序,但仍然没有响应。

服务器代码..

public class SimpleChatServer {
static int port_num =4444;
public static void main(String[] args) {

ServerSocket serverSocket = null;
Socket clientSocket = null;

try {
serverSocket = new ServerSocket(port_num);
System.out.println("Server started. Listening to the port 4444. Waitng for the client.");
clientSocket = serverSocket.accept();
System.out.println("Client connected on port 4444.");
port_num++;
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
e.printStackTrace();
return;
}

请哪位大侠告诉我该怎么办?如何将客户端连接到服务器? ipconfig 的 ip 地址是什么,google 的 ip 公共(public)地址是什么?

这是我的安卓客户端代码。

     public class SimpleClientServerChatActivity extends Activity {

private EditText textField,ipaddrs;
private Button button, start;
private TextView textView;
private Socket client;
private PrintWriter printwriter;
private BufferedReader bufferedReader;

//Following is the IP address of the chat server. You can change this IP address according to your configuration.
// I have localhost IP address for Android emulator.
private String CHAT_SERVER_IP = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple_client_server_chat);
textField = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
textView = (TextView) findViewById(R.id.textView1);
ipaddrs = (EditText) findViewById(R.id.ipaddrs);
start = (Button) findViewById(R.id.start);

start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
###############// there client enter server public ip address via mobile app
CHAT_SERVER_IP = String.valueOf(ipaddrs.getText());
ChatOperator chatOperator = new ChatOperator();
chatOperator.execute();
}
});



}

/**
* This AsyncTask create the connection with the server and initialize the
* chat senders and receivers.
*/
private class ChatOperator extends AsyncTask<Void, Void, Void> {

@Override
protected Void doInBackground(Void... arg0) {
try {
client = new Socket(CHAT_SERVER_IP, 4444); // Creating the server socket.

if (client != null) {
printwriter = new PrintWriter(client.getOutputStream(), true);
InputStreamReader inputStreamReader = new InputStreamReader(client.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
} else {
System.out.println("Server has not bean started on port 4444.");
}
} catch (UnknownHostException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
} catch (IOException e) {
System.out.println("Faild to connect server " + CHAT_SERVER_IP);
e.printStackTrace();
}
return null;
}

/**
* Following method is executed at the end of doInBackground method.
*/
@Override
protected void onPostExecute(Void result) {
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final Sender messageSender = new Sender(); // Initialize chat sender AsyncTask.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
messageSender.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
messageSender.execute();
}
}
});

Receiver receiver = new Receiver(); // Initialize chat receiver AsyncTask.
receiver.execute();

}

}

/**
* This AsyncTask continuously reads the input buffer and show the chat
* message if a message is availble.
*/
private class Receiver extends AsyncTask<Void, Void, Void> {

private String message;

@Override
protected Void doInBackground(Void... params) {
while (true) {
try {

if (bufferedReader.ready()) {
message = bufferedReader.readLine();
publishProgress(null);
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
}
}

@Override
protected void onProgressUpdate(Void... values) {
textView.append("Server: " + message + "\n");
}

}

/**
* This AsyncTask sends the chat message through the output stream.
*/
private class Sender extends AsyncTask<Void, Void, Void> {

private String message;

@Override
protected Void doInBackground(Void... params) {
message = textField.getText().toString();
printwriter.write(message + "\n");
printwriter.flush();

return null;
}

@Override
protected void onPostExecute(Void result) {
textField.setText(""); // Clear the chat box
textView.append("Client: " + message + "\n");
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_simple_client_server_chat, menu);
return true;
}



@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

当我输入服务器公共(public) IP 地址时出现问题移动应用程序崩溃。为什么会这样。如果我把本地 IP 地址放在那里,它就不会崩溃。

最佳答案

您必须在具有公共(public) IP 的服务器上运行您的 jar 文件。您计算机上的地址是您的本地 IP。更重要的是,有时 WiFi 接入点可以在公共(public)场所(例如麦当劳、Edurom、肯德基等)阻止端口 4444。你必须记住这一点。

所以,用公网IP配置你自己的服务器,启动你的服务器

java -jar server.jar

然后测试一下。

例如,它是 Edurom(大学 WiFi)中的可用端口列表。就像我伤心一样,端口 4444 在这里被阻止了。 enter image description here

关于Java服务器android客户端通过不同网络进行通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31661258/

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