我正在尝试创建一个使用套接字连接到 php 服务器的 Android 应用程序。下面是我用于实现套接字服务器的 php 代码。
<?php
set_time_limit (0);
$address = '127.0.0.1';
$port = 8111;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, $address, $port) or die('Could not bind to address');
socket_listen($sock);
$client = socket_accept($sock);
$input = socket_read($client, 1024);
$output = $input;
socket_write($client, $output);
socket_close($client);
socket_close($sock);
?>
Android客户端代码:
package com.example.simpleclient;
import com.example.simpleclient.util.SystemUiHider;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.view.View;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class FullscreenActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "192.168.2.11";
// AND THAT'S MY DEV'T MACHINE WHERE PACKETS TO
// PORT 5000 GET REDIRECTED TO THE SERVER EMULATOR'S
// PORT 6000
private static final int REDIRECTED_SERVERPORT = 8111;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
bt = (Button) findViewById(R.id.myButton);
tv = (TextView) findViewById(R.id.myTextView);
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
bt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(str);
Log.d("Client", "Client sent message");
} catch (UnknownHostException e) {
tv.setText("Error1");
e.printStackTrace();
} catch (IOException e) {
tv.setText("Error2");
e.printStackTrace();
} catch (Exception e) {
tv.setText("Error3");
e.printStackTrace();
}
}
});
}
}
192.168.2.11 是我托管服务器的系统的 ip。我附上了我的 android 代码中断的调试器屏幕截图。请看一看。
我无法将 android 应用程序连接到 php 服务器