Server:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using UnityEngine;
public class SocketServer : MonoBehaviour
{
//配置相关;
public string _ip = "10.19.201.92";
//1024,65535 端口范围;
public int _port = 6666;
//服务器套接字;
private Socket _server;
//接受客户端连接的线程,因为Accept是一个阻赛线程的方法,而且此方法还需要循环执行;
// accept Client Connect Thread 接受 客户端 连接 线程
private Thread _acceptClientConnectThread;
//所有已经连接的客户端;
private List<Socket> _clientList = new List<Socket>();
private void Start()
{
CreatServer();
}
/// <summary>
/// 启动服务器=建立流式套接字+配置本地地址;
/// </summary>
public void CreatServer()
{
try
{
//固定格式 寻址方案 套接字类型 协议类型
_server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//配置本地地址中 向量转换;
EndPoint endPoint = new IPEndPoint(IPAddress.Parse(_ip), _port);
//配置本地地址;
_server.Bind(endPoint);
//监听和接受客户端请求的数量;
_server.Listen(30);
//接受客户端连接 运行时需要防火墙许可;
//_server.Accept();
//单线程无法继续进行,引入多线程;
_acceptClientConnectThread = new Thread(AcceptClientConnect);
_acceptClientConnectThread.Start();
服务器的前四步检测;
Debug.Log("监听成功!");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
/// <summary>
/// Accept Client Connect接受 客户端 连接;
/// </summary>
public void AcceptClientConnect()