【发布时间】:2015-07-27 19:05:22
【问题描述】:
我正在实现聊天应用程序,其中服务器基于 java,客户端在 android。我的服务器代码是使用套接字编程用 java 语言编写的。当我将我的 android 手机(互联网已打开)与笔记本电脑连接并启动服务器和客户端时,它工作正常。在我的客户端应用程序中,我必须输入服务器机器的 IP 地址,例如 192.168..。当客户端向服务器发送消息时,服务器向客户端返回响应。没关系。
但是当我从不在我家庭网络中的其他 android 手机运行客户端时(假设我的朋友在他家并尝试通过互联网与 java 服务器(在我家中)连接)。然后服务器没有显示连接建立. 我也尝试在启动时将我的公共 IP 地址从 google 放入客户端应用程序,但仍然没有响应。
服务器代码..
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 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);
}
}
当我输入服务器公共 IP 地址移动应用程序崩溃时出现问题。为什么会这样。如果我把本地IP地址放在那里,它就不会崩溃。
【问题讨论】:
-
如果您尝试通过网络连接,您可能需要通过路由器查看端口转发。
-
我知道端口转发。但我正在通过手机访问互联网。所以我这边没有路由器。那么我该如何使用端口转发。
-
是的,但是您正在尝试连接到在其他地方运行服务器的计算机,我正确吗?
-
我说清楚....我的笔记本电脑变成了我的服务器,而笔记本电脑(服务器)正在使用我的手机(android)连接互联网(3G)。行。现在我的客户是另一部不在我网络中的手机(android)。假设我家的朋友尝试连接我的服务器(笔记本电脑)。所以这次如果我在客户端应用程序(android)中使用我的公共 IP 地址连接它失败。为什么会这样?
-
啊,那我就不知道了。对不起。通常在任何需要使用公共 IP 地址的情况下,您都需要端口转发到服务器。但由于没有路由器,我不知道如何做到这一点。
标签: java android sockets client-server