嗨,我是这些类型的新手,但这是我想要做的。套接字PHP服务器不显示从Android客户端发送的消息
我试图实现一个聊天应用程序,用户将从网站发送他们的查询,并且一旦这些消息被网站用户发送,它就会出现在网站所有者的android手机应用程序中,他们会回答他们的疑问。简而言之,我想实施一个实时聊天。
现在我只是简单地尝试从android应用程序发送消息到php服务器。 但是,当我运行我的PHP脚本从Dreamweaver铬浏览器不断加载,并不显示任何输出时,我从客户端发送消息。
有时候会发生这样的情况,php脚本显示了我从android(客户端)发送的一些输出。但是我不知道它何时起作用,何时不起作用。
所以我想在我从客户端发送这些消息后立即在php脚本中显示这些消息,反之亦然(客户端没有实现,反之亦然)。
这是我迄今为止所做的。
php脚本:
<?php
set_time_limit (0);
$address = '127.0.0.1';
$port = 1234;
$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);
$welcome = "Roll up, roll up, to the greatest show on earth!\n? ";
socket_write($client, $welcome,strlen($welcome)) or die("Could not send connect string\n");
do{
$input=socket_read($client,1024,1) or die("Could not read input\n");
echo "User Says: \n\t\t\t".$input;
if (trim($input) != "")
{
echo "Received input: $input\n";
if(trim($input)=="END")
{
socket_close($spawn);
break;
}
}
else{
$output = strrev($input) . "\n";
socket_write($spawn, $output . "? ", strlen (($output)+2)) or die("Could not write output\n");
echo "Sent output: " . trim($output) . "\n";
}
}
while(true);
socket_close($sock);
echo "Socket Terminated";
?>
的Android代码:
public class ServerClientActivity extends Activity {
private Button bt;
private TextView tv;
private Socket socket;
private String serverIpAddress = "127.0.0.1";
private static final int REDIRECTED_SERVERPORT = 1234;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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(e.getMessage());
e.printStackTrace();
}
catch (IOException e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
catch (Exception e)
{
tv.setText(e.getMessage());
e.printStackTrace();
}
}
});
}
}
我刚刚粘贴的文本Android.Edit的onclick按钮事件的代码是我要去的地方,进入了我的文字文本框。 IP地址和端口与php脚本中的相同。
这可能有点偏离主题,您可以在我的上一篇文章中获得一些灵感和有用的建议。 https://stackoverflow.com/questions/29159354/php-socket-with-android/45851814#45851814 这里是一些非常有用的代码,可以帮助你下载。 http://developersfound.com/PHP_SocketServer_Android_SocketClient.zip – user2288580