php服务器脚本简单例子,简单的PHP NAT穿过服务器脚本

我正在尝试编写一个可以充当“主服务器”的PHP脚本,并且可以方便两个Java游戏客户端之间的P2P连接。我正在使用允许主服务器访问端口的共享Web主机。

对于初学者,我想测试主服务器和java客户端之间的UDP套接字连接。这是我的PHP脚本,名为“masterServer.php”

error_reporting(E_ALL);

set_time_limit(40); // Allow script to execute for at most 40 seconds.

$myFile = "output.txt";

$fh = fopen($myFile, 'w');

if ($socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP))

{

if(socket_bind($socket,0, 2005))

{

$clientAddress = 0;

$clientPort = 0;

fwrite($fh, "Start at: ".time());

fwrite($fh, "Waiting for socket at ".time());

if(socket_recvfrom($socket, &$udp_buff, 23, MSG_WAITALL, &$clientAddress, &$clientPort)) // BLOCKING METHOD

{

fwrite($fh, print_r($udp_buff, true));

}

else

{

echo(socket_strerror(socket_last_error()));

die();

}

}

else

{

echo(socket_strerror(socket_last_error()));

die();

}

}

else

{

echo(socket_strerror(socket_last_error()));

die();

}

fwrite($fh, "End at: ".time());

fclose($fh);

?>我访问masterServer.php让脚本运行,几秒钟后,我启动一个简单的Java应用程序,它应该向主服务器发送UDP数据包。以下是Java应用程序的代码:

package comm;

import java.io.IOException;

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

import java.net.SocketException;

public class UDPSocket

{

public static void main (String[] asdf)

{

try

{

String host = ;

int port = 2005;

byte[] message = "Java Source and Support".getBytes();

// Get the internet address of the specified host

InetAddress address = InetAddress.getByName(host);

// Initialize a datagram packet with data and address

DatagramPacket packet = new DatagramPacket(message, message.length,

address, port);

// Create a datagram socket, send the packet through it, close it.

DatagramSocket dsocket = new DatagramSocket();

dsocket.send(packet);

dsocket.close();

}

catch (SocketException e)

{

e.printStackTrace();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}根据我的理解,PHP服务器没有收到UDP数据包。该脚本不会继续通过阻塞的socket_recvfrom()方法,也不会将UDP数据包的内容写入输出文本文件。谁能帮我吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值