[英]Java TCP socket server with PHP client?
Hey there , 嘿那里 ,
I am developing an TCP socket server in Java. 我正在用Java开发TCP套接字服务器。 The client(s) must connect to a webpage (in PHP) 客户端必须连接到网页(在PHP中)
Well, here come's my trouble.. They can connect to the specified host, but the server can't read the packets that the client send. 好吧,这就是我的麻烦..他们可以连接到指定的主机,但服务器无法读取客户端发送的数据包。
If I create the client in Java, it works 100%. 如果我用Java创建客户端,它可以100%工作。 Well, here are some snippets of my code. 好吧,这是我的代码的一些片段。 I hope someone have a answer for me. 我希望有人能给我一个答案。 Because I'm stuck. 因为我被困住了。
This is my little PHP script that sends: 这是我发送的小PHP脚本:
<?php
set_time_limit(0);
$PORT = 1337; //the port on which we are connecting to the "remote" machine
$HOST = "localhost"; //the ip of the remote machine (in this case it's the same machine)
$sock = socket_create(AF_INET, SOCK_STREAM, 0) //Creating a TCP socket
or die("error: could not create socket\n");
$succ = socket_connect($sock, $HOST, $PORT) //Connecting to to server using that socket
or die("error: could not connect to host\n");
$text = "wouter123"; //the text we want to send to the server
socket_sendto($sock, $text, strlen($message), MSG_EOF, '127.0.0.1', '1337');
//socket_write($sock, $text . "\n", strlen($text) + 1) //Writing the text to the socket
// or die("error: failed to write to socket\n");
$reply = socket_read($sock, 10000, PHP_NORMAL_READ) //Reading the reply from socket
or die("error: failed to read from socket\n");
echo $reply;
?>
The socket side is: 套接字侧是:
package com.sandbox.communication;
public class PacketHandler {
public String processInput(String theInput) {
String theOutput = null;
if (theInput == "wouter123") {
theOutput = theInput;
}else {
theOutput = "Cannot find packet. The output packet is " + theInput;
}
return theOutput;
}
} }
And this little code connects to the PacketHandler: PacketHandler ph = new PacketHandler(); 这个小代码连接到PacketHandler:PacketHandler ph = new PacketHandler();
while ((inputLine = in.readLine()) != null)
{
outputLine = ph.processInput(inputLine);
out.println(outputLine);
}
As you are using readLine on your input stream so make sure your clients are sending the data with linefeed. 当您在输入流上使用readLine时,请确保您的客户端使用换行符发送数据。
readLine() Reads a line of text. readLine()读取一行文本。 A line is considered to be terminated by any one of a line feed ('\\n'), a carriage return ('\\r'), or a carriage return followed immediately by a linefeed. 一条线被认为是由换行符('\\ n'),回车符('\\ r')或回车符中的任何一个终止,后面紧跟换行符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.