公司给一个项目要求程序发布WebGL端同时连接pgSQL与Socket服务器,因为Unity WebGL是无法连接数据库与Socket通讯的,所以就通过PHP作为中间转接层来获取数据,代码如下:
注:PHP需要搭建环境,推荐Wampserver。
GitHub:https://github.com/baishuisr1/-Unity-Connect-the-pgSQL-with-the-Socket-server-via-PHP
演示(由于PHP不支持多线程,所以是间隔时间来获取数据):
Unity PHP连接服务器.gif
数据库截图:
%E6%88%AA%E5%.png
服务器代码:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Xml;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
Program program = new Program();
program.StartServer();
Console.ReadKey();
}
void StartServer() //服务器异步连接
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("x.x.x.x"); //设置IP
IPEndPoint ipEndPoint = new IPEndPoint(ipAddress,xxxx); //设置IP和端口号
socket.Bind(ipEndPoint); //绑定IP和端口号
socket.Listen(0); //开始监听客户端
socket.BeginAccept(AcceptCallBack, socket); //通过BeginAccept进行异步连接
Console.ReadKey();
}
void AcceptCallBack(IAsyncResult ar)
{
Console.WriteLine("有一个客户端连接了");
Socket socket = ar.AsyncState as Socket;
Socket clientSocket = socket.EndAccept(ar);
//向客户端发送一条消息
string date = "服务器连接成功";
byte[] msg = System.Text.Encoding.UTF8.GetBytes(date);
clientSocket.Send(msg);
clientSocket.BeginReceive(dateBuffer, 0, 1024, SocketFlags.None, ReceiveCallBcak, clientSocket);
socket.BeginAccept(AcceptCallBack, socket);
}
static byte[] dateBuffer = new byte[1024];
private int i=1;
void ReceiveCallBcak(IAsyncResult ar) //事件,ar传递值
{
Socket clientSocket = null;
try
{
clientSocket = ar.AsyncState as Socket;
int count = clientSocket.EndReceive(ar);
string msg = Encoding.UTF8.GetString(dateBuffer, 0, count);//获取客户端发来数据
Console.WriteLine("客户端发送消息:" + msg);
i++;
Thread.Sleep(2000);//等待2秒再次发送数据
byte[] date = Encoding.UTF8.GetBytes(i.ToString());
clientSocket.Send(date);//发送数据
Console.WriteLine("服务器发送数据:" + Encoding.UTF8.GetString(date));
clientSocket.BeginReceive(dateBuffer, 0, 1024, SocketFlags.None, ReceiveCallBcak, clientSocket);
}
catch (Exception)
{
Console.WriteLine("客户端断开连接");
}
}
}
}
PHP代码:
<?php
//连接数据库
$conn = pg_connect("host=127.0.0.1 port=5432 dbname=xxxxx user=postgres password=xxxxx");
$str = "select * from \"Test\"";
$ret = pg_query($conn,$str);
while($row = pg_fetch_row($ret)){
echo $row[0];//输出数据库ID[1]
echo $row[1];//输出数据库ID[2]
}
//连接SOCKET
$host = "x.x.x.x";
$port= "xxxx";
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$result=socket_connect($socket,$host,$port);
$budder=@socket_read($socket,1024);//接受Scket数据
echo $budder;
$userid=$_POST['msg'];//获取unity发来数据
socket_write($socket,$userid); //将unity数据发送到socket
$budder=@socket_read($socket,1024);//重新接受unity数据
echo $budder;
socket_close($socket);
?>
Unity 代码:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class NewBehaviourScript : MonoBehaviour
{
public GameObject text;
// Use this for initialization
void Start()
{
StartCoroutine(IGetData());
}
// Update is called once per frame
void Update()
{
}
IEnumerator IGetData()
{
while (true)
{
WWWForm form = new WWWForm();
form.AddField("msg", "Server");//设置发送数据
WWW www = new WWW("http://127.0.0.1/index.php", form);//下载与上传数据
yield return www; //等待Web服务器
text.GetComponent<Text>().text = www.text;
Debug.Log(www.text);
}
}
}
网友评论