我正在尝试从PHP套接字连接到客户端套接字以发送消息。
这是PHP服务器套接字代码:
<?php
error_reporting(E_ALL);
ob_implicit_flush();
$address = '192.168.1.7';
// $address = 'www.xxxxxx.com';
$port = 15986;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
echo"socket created";
socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($sock, $address, $port);
socket_listen($sock);
$clients = array($sock);
while (true)
{
$read = $clients;
$write = null;
$except = null;
if (socket_select($read, $write, $except, 0) < 1)
continue;
if (in_array($sock, $read))
{
$clients[] = $newsock = socket_accept($sock);
socket_getpeername($newsock, $ip, $port);
echo "New client connected: {$ip}\n";
$key = array_search($sock, $read);
unset($read[$key]);
}
foreach ($read as $read_sock)
{
$data = @socket_read($read_sock, 4096, PHP_BINARY_READ);
$data = trim($data);
if ($data == "false")
{
$key = array_search($read_sock, $clients);
unset($clients[$key]);
echo "client disconnected.\n";
continue;
}
if (!empty($data))
{
echo " send {$data}\n";
// do sth..
socket_write($read_sock, $data);
}
}
}
socket_close($sock); // close the listening socket
?>
用于向服务器发送消息的java(Android)代码:
btnSendMessage.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
sendMessage(sendMsg.getText().toString());
}
});
}
private void sendMessage(String message) {
try {
if (null != socket) {
if (!socket.isClosed()) {
outputStream = socket.getOutputStream();
OutputStreamWriter outputStreamWriter = new
OutputStreamWriter(outputStream);
PrintWriter out = new PrintWriter(new BufferedWriter(outputStreamWriter),
true);
out.println(message);
if (message.equals("false"))
{
inputStream.close();
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
OnClickListener buttonConnectOnClickListener =
new OnClickListener(){
@Override
public void onClick(View arg0) {
MyClientTask myClientTask = new MyClientTask(
Constants.SOCKET_URL,
Constants.SOCKET_PORT);
myClientTask.execute();
}};
public class MyClientTask extends AsyncTask<String, String, String> {
String dstAddress;
int dstPort;
String response = "";
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
@Override
protected String doInBackground(String... arg0) {
try {
socket = new Socket(dstAddress, dstPort);
isSocketConnected = true;
Log.i(TAG, "Socket connected" );
ByteArrayOutputStream byteArrayOutputStream =new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
inputStream = socket.getInputStream();
/*
* notice:
* inputStream.read() will block if no data return
*/
if (!socket.isClosed()) {
if (isSocketConnected ) {
while ((bytesRead = inputStream.read(buffer)) != -1 ) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response = byteArrayOutputStream.toString("UTF-8");
byteArrayOutputStream.reset();
Log.i(TAG,response);
}
}
}
return response;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
}/*finally{
if(socket != null){
try {
isSocketConnected = false;
sendMessage("false");
Log.i(TAG,"Socket going to disconnect in finally");
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
@Override
protected void onPostExecute(String result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
@Override
protected void onPause() {
super.onPause();
/*if(socket != null){
try {
isSocketConnected = false;
sendMessage("false");
outputStream.close();
Log.i(TAG,"Socket going to disconnect in onPause");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}*/
}
但是,从服务器收到以下400错误。请注意,这仅在连接到远程服务器时发生,它在本地运行时都有效:
HTTP/1.1 400 Bad Request
Date: Mon, 14 May 2018 13:55:43 GMT
Server: Apache
Content-Length: 347
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br /></p>
<p>Additionally, a 400 Bad Request error was encountered while trying to use an ErrorDocument to handle the request.</p>
</body></html>