</pre><p><strong><span style="font-size:24px"><span style="white-space:pre"></span>其实在unity脚本中编写socket的服务器与平时编写差别并不大,只需注意如何将代码分配到脚本中特有的start与update方法。下面附上一段脚本实例,用来接收客户端传过来的数据</span></strong></p><p><strong><span style="font-size:24px"></span></strong></p><pre name="code" class="csharp"><pre name="code" class="csharp">using UnityEngine;
using System.Collections;
using System;
using System.Net.Sockets;
using System.Net;
using System.Text;
public class control : MonoBehaviour
{
private Vector3 xMovement;
private Vector3 yMovement;
private Vector3 movement;
// Use this for initialization
void Start()
{
int recv;
byte[] data = new byte[1024];
float[] speed = new float[10];
for(int j=0;j<10;j++)
{
speed[j] = 0;
}
float xSpeed=0;
float ySpeed=0;
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9051);//本机预使用的IP和端口
System.Net.Sockets.Socket client = null;
System.Net.Sockets.Socket newsock = new System.Net.Sockets.Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
newsock.Bind(ipep);//绑定
newsock.Listen(10);//Debug.Log("Hello");
Debug.Log("Hello");
// Console.WriteLine("waiting for a client");
while (client == null)
{
client = newsock.Accept();//当有可用的客户端连接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
}
// IPEndPoint clientip = (IPEndPoint)client.RemoteEndPoint;
//Console.WriteLine("connect with client:" + clientip.Address + " at port:" + clientip.Port);
// string welcome = "welcome here!";
// data = Encoding.ASCII.GetBytes(welcome);
// client.Send(data, data.Length, SocketFlags.None);//发送信息
int i = 0;
while (true)
{//用死循环来不断的从客户端获取信息
data = new byte[1024];
recv = client.Receive(data);
speed[i] = float.Parse(Encoding.UTF8.GetString (data, 0, recv));
Console.WriteLine("123");
i++;
if (i == 2)
{
i = 0;
break;
}
}
xSpeed = speed[0];
ySpeed = speed[1];
xMovement = Vector3.right * (xSpeed/10);
yMovement = Vector3.forward * (ySpeed/10);
movement = xMovement + yMovement;
}
// Update is called once per frame
void Update()
{
//Rigidbody body = GetComponent<Rigidbody>();
//body.AddForce(movement, ForceMode.Force);
transform.Translate(movement * Time.deltaTime);
}
}