Unity Socket网络编程坑挺多的,服务端在VS能好好运行的代码,在unity中得开启线程去执行,要不然会在Socket.Accept卡死。
服务端代码
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Collections.Generic;
using System.Threading;
public class Parent : MonoBehaviour
{
static List<Client> clientList = new List<Client>();//建立一个集合
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Thread t;
// Use this for initialization
void Start()
{
tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.100.30"), 8899));
Debug.Log("服务端启动完成");
tcpServer.Listen(100);
t = new Thread(Connection);
t.Start();
}
public void Connection()
{
while (true)
{
Socket clienttSocket = tcpServer.Accept(); //暂停线程直到用户连接
Client client = new Client(clienttSocket);//把与每个客户端的逻辑放到client的对象里
clientList.Add(client);
}
}
}
里面还调用了Client类(在Client类中加了一个线程读取客户端发送过来的消息)
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
public class Client
{
private Socket clientSocket;
private Thread t;
private byte[] data = new byte[1024];//这个是一个数据容器
public string message;
public Client(Socket s)
{
clientSocket = s;
//启动一个线程 处理客户端的数据接收
t = new Thread(ReceiveMessage);
t.Start();
}
private void ReceiveMessage()
{
//一直接收客户端的数据
while (true)
{
//在接收数据之前 判断一下socket连接是否断开
if (clientSocket.Poll(10, SelectMode.SelectRead))
{
clientSocket.Close();
break;//跳出循环 终止线程的执行
}
int length = clientSocket.Receive(data);
message = Encoding.UTF8.GetString(data, 0, length);
}
}
其中需要注意的是:
1、Accept()必须在线程中执行,要不然会导致Unity程序无法运行;
2、线程不能在update里new,要不然会因为无限循环导致栈溢出。
3、最重要的一点,要想服务端起作用,必须导出exe后才行,在编辑器中运行是不起作用的。(在下因为这个调了好久!!!)
客户端代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class Children : MonoBehaviour
{
// Start is called before the first frame update
//1、创建socket
Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
void Start()
{
//2、发起连接的请求
IPAddress ipaddress = IPAddress.Parse("192.168.100.30");//可以把一个字符串的ip地址转化成一个IPaddress的对象
EndPoint point = new IPEndPoint(ipaddress, 8899);
tcpClient.Connect(point);//通过ip:端口号 定位一个要连接的服务器端
}
// Update is called once per frame
void Update()
{
if (buttonUI.isSetMessage)
{
string message2 ="我连进来啦!";//用户输入 给客户端的信息
tcpClient.Send(Encoding.UTF8.GetBytes(message2));//把字符串转化成字节数组,然后发送到服务器端
Debug.Log(message2);
}
}
}
记得IP号和端口号要和服务端的对应(代码中的ip需要自己修改后使用)
就酱紫啦!