嘿那里,
我正在用 Java 开发一个 TCP 套接字服务器。客户端必须连接到网页(在 PHP 中)
好吧,我的麻烦来了。他们可以连接到指定的主机,但是服务器无法读取客户端发送的数据包。
如果我用 Java 创建客户端,它可以 100% 工作。好吧,这是我的一些代码片段。我希望有人能给我一个答案。因为我被困住了。
这是我发送的小 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;
?>
插座端是:
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;
}
}
这个小代码连接到 PacketHandler: PacketHandler ph = new PacketHandler();
while ((inputLine = in.readLine()) != null)
{
outputLine = ph.processInput(inputLine);
out.println(outputLine);
}