PHP服务器 c#客户端 UDPSocket 连接

php命令行 需要将你的php添加到环境变量 

PHP server:

这个UnitySocketMsg.php 用来保存订阅信息

<?php
// 面向对象思维
include 'UnitySocketMsg.php';

$ss = new MySocketServer();
$ss->setVariale();
$ss->init();
class MySocketServer 
{
	var $socket;
	var $from;
	var $port;

	function setVariale(){
		$this->socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
		$this->from = '';
		$this->port = 0;
	}

	function init(){
		error_reporting(E_ALL | E_STRICT);

		socket_bind($this->socket, '192.168.0.110', 9000);

		while (1) {
	// 接收 接收到untiy c#客户端的短连接
			socket_recvfrom($this->socket, $buf, 30, 0, $this->from, $this->port);
			echo "Received $buf from remote address $this->from and remote port $this->port" . PHP_EOL;
			
	// 返回c# 客户端需要查询的 订阅信息
			$msg="subscription";
			$len = strlen("$msg");
			socket_sendto($this->socket,"$msg" ,$len,0,$this->from, $this->port);			
		}
	}
}

// 面向过程思维
// error_reporting(E_ALL | E_STRICT);
// $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);
// socket_bind($socket, '192.168.0.110', 9000);
// $from = '';
// $port = 0;
// $msg = "nosubscriber";


// while (1) {
// 	# code...
// 	socket_recvfrom($socket, $buf, 12, 0, $from, $port);
// 	echo "Received $buf from remote address $from and remote port $port" . PHP_EOL;

// 	$len = strlen($msg);
// 	socket_sendto($socket,$msg ,$len,0,$from, $port);
// }
?>

c# Client:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

// Client app is the one sending messages to a Server/listener.   
// Both listener and client can send messages back and forth once a   
// communication is established.  
public class SocketClient
{
    public static int Main(String[] args)
    {
        //StartClient();
        string sendString = null;//要发送的字符串 
        byte[] sendData = null;//要发送的字节数组 
        UdpClient client = null;
        string receiveString = null;
        byte[] receiveData = null;

        //IPAddress remoteIP = IPAddress.Parse("127.0.0.1"); //假设发送给这个IP
        IPAddress remoteIP = IPAddress.Parse("192.168.0.110"); //假设发送给这个IP
        // u3d发送端口 9000是发送端口
        int remotePort = 9000;
        IPEndPoint remotePoint = new IPEndPoint(remoteIP, remotePort);//实例化一个远程端点 

        while (true)
        {
            sendString = Console.ReadLine();
            //sendString = "client!!!";
            sendData = Encoding.Default.GetBytes(sendString);

            client = new UdpClient();
            client.Send(sendData, sendData.Length, remotePoint);//将数据发送到远程端点 
            receiveData = client.Receive(ref remotePoint);//接收数据
            receiveString = Encoding.Default.GetString(receiveData);
            Console.WriteLine(remotePoint.Address + receiveString);
            client.Close();//关闭连接 

        }

        return 0;
    }


    public static void StartClient()
    {
        byte[] bytes = new byte[1024];

        try
        {
            // Connect to a Remote server  
            // Get Host IP Address that is used to establish a connection  
            // In this case, we get one IP address of localhost that is IP : 127.0.0.1  
            // If a host has multiple addresses, you will get a list of addresses  
            IPHostEntry host = Dns.GetHostEntry("localhost");
            IPAddress ipAddress = host.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);

            // Create a TCP/IP  socket.    
            Socket sender = new Socket(ipAddress.AddressFamily,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect the socket to the remote endpoint. Catch any errors.    
            try
            {
                // Connect to Remote EndPoint  
                sender.Connect(remoteEP);

                Console.WriteLine("Socket connected to {0}",
                    sender.RemoteEndPoint.ToString());

                // Encode the data string into a byte array.    
                byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

                // Send the data through the socket.    
                int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.    
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Echoed test = {0}",
                    Encoding.ASCII.GetString(bytes, 0, bytesRec));

                // Release the socket.    
                sender.Shutdown(SocketShutdown.Both);
                sender.Close();

            }
            catch (ArgumentNullException ane)
            {
                Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
            }
            catch (SocketException se)
            {
                Console.WriteLine("SocketException : {0}", se.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception : {0}", e.ToString());
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }
}

如果你需要使用的是 c# 服务器:

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

// Socket Listener acts as a server and listens to the incoming   
// messages on the specified port and protocol.  
public class SocketListener
{
    public static int Main(String[] args)
    {
        //StartServer();
        UdpClient client = null;
        string receiveString = null;
        byte[] receiveData = null;
        //实例化一个远程端点,IP和端口可以随意指定,等调用client.Receive(ref remotePoint)时会将该端点改成真正发送端端点 
        IPEndPoint remotePoint = new IPEndPoint(IPAddress.Any, 0);

        while (true)
        {
            // u3d接收端口
            client = new UdpClient(9000);
            
            receiveData = client.Receive(ref remotePoint);//接收数据 
            client.Send(receiveData, receiveData.Length, remotePoint);//将数据发送到远程端点 
            receiveString = Encoding.Default.GetString(receiveData);
            Console.WriteLine(remotePoint.Address + receiveString);
            client.Close();//关闭连接 
        }

        return 0;
    }


    public static void StartServer()
    {
        // Get Host IP Address that is used to establish a connection  
        // In this case, we get one IP address of localhost that is IP : 127.0.0.1  
        // If a host has multiple addresses, you will get a list of addresses  
        IPHostEntry host = Dns.GetHostEntry("localhost");
        IPAddress ipAddress = host.AddressList[0];
        IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);


        try
        {

            // Create a Socket that will use Tcp protocol      
            Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            // A Socket must be associated with an endpoint using the Bind method  
            listener.Bind(localEndPoint);
            // Specify how many requests a Socket can listen before it gives Server busy response.  
            // We will listen 10 requests at a time  
            listener.Listen(10);

            Console.WriteLine("Waiting for a connection...");
            Socket handler = listener.Accept();

            // Incoming data from the client.    
            string data = null;
            byte[] bytes = null;

            while (true)
            {
                bytes = new byte[1024];
                int bytesRec = handler.Receive(bytes);
                data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
                if (data.IndexOf("<EOF>") > -1)
                {
                    break;
                }
            }

            Console.WriteLine("Text received : {0}", data);

            byte[] msg = Encoding.ASCII.GetBytes(data);
            handler.Send(msg);
            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\n Press any key to continue...");
        Console.ReadKey();
    }
}

PHP Client:

<?php

/*
	Simple php udp socket client
*/

//Reduce errors
error_reporting(~E_WARNING);

$server = '127.0.0.1';
$port = 9000;

if(!($sock = socket_create(AF_INET, SOCK_DGRAM, 0)))
{
	$errorcode = socket_last_error();
    $errormsg = socket_strerror($errorcode);
    
    die("Couldn't create socket: [$errorcode] $errormsg \n");
}

echo "Socket created \n";

//Communication loop
while(1)
{
	//Take some input to send
	echo 'Enter a message to send : ';
	//$input = fgets(STDIN);
	$input= "php";
	//Send the message to the server
	if( ! socket_sendto($sock, $input , strlen($input) , 0 , $server , $port))
	{
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		
		die("Could not send data: [$errorcode] $errormsg \n");
	}
		
	//Now receive reply from server and print it
	if(socket_recv ( $sock , $reply , 2045 , MSG_WAITALL ) === FALSE)
	{
		$errorcode = socket_last_error();
		$errormsg = socket_strerror($errorcode);
		
		die("Could not receive data: [$errorcode] $errormsg \n");
	}
	
	echo "Reply : $reply";
}