Unity 网络编程(Socket)应用

服务端:

/***
 * 
 * 
 *  服务器端 
 * 
 */

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

using System.Text;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using UnityEngine.UI;
using System;

public class Server : MonoBehaviour
{
    public InputField InpIPAdress;                              //IP地址
    public InputField InpPort;                                  //端口号
    public InputField InpDisplayInfo;                           //显示信息
    public InputField InpSendMsg;                               //发送信息
    public Dropdown Dro_IPList;                                 //客户端的IP列表

    private Socket socketServer;                                //服务端套接字
    private bool IsListionContect;                              //是否监听
    private StringBuilder _strDisplayInfo = new StringBuilder();//追加信息
    private string _CurClientIPValue = string.Empty;            //当前选择的IP地址
    //保存客户端通讯的套接字
    private Dictionary<string, Socket> _DicSocket = new Dictionary<string, Socket>();
    //保存DropDown的数据,目的为了删除节点信息
    private Dictionary<string, Dropdown.OptionData> _DicDropdowm = new Dictionary<string, Dropdown.OptionData>();

    // Start is called before the first frame update
    void Start()
    {
        //控件初始化
        InpIPAdress.text = "127.0.0.1";
        InpPort.text = "1000";
        InpSendMsg.text = string.Empty;
        
        //下拉列表处理
        Dro_IPList.options.Clear();                         //清空列表信息
        //添加一个空节点
        Dropdown.OptionData op = new Dropdown.OptionData();
        op.text = "";
        Dro_IPList.options.Add(op);
    }

    /// <summary>
    /// 退出系统
    /// </summary>
    public void ExitSystem()
    {
        if (socketServer != null)
        {
            socketServer.Shutdown(SocketShutdown.Both);     //关闭连接
            socketServer.Close();                           //清理资源
        }
        Application.Quit();
    }

    /// <summary>
    /// 获取当前好友
    /// </summary>
    public void GetCurrentIPInformation()
    {
        //选择玩家当前列表
        _CurClientIPValue = Dro_IPList.options[Dro_IPList.value].text;
    }

    public void EnableServerReady()
    { 
        //需要绑定地址和端口号
        IPEndPoint endPoint = new IPEndPoint(IPAddress.Parse(InpIPAdress.text), Convert.ToInt32(InpPort.text));
        //定义监听Socket
        socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        //绑定
        socketServer.Bind(endPoint);

        //开始socket监听
        socketServer.Listen(10);
        //显示内容
        //定义方法

        //开启前台监听(监听客户端连接)
        Thread thClientCon = new Thread(ListionCilentCon);
        thClientCon.Name = "thListionClientCon";
        thClientCon.Start();
    }

    private void ListionCilentCon()
    {
        Socket socMesgServer = null;                        //会话Socket

        try
        {
            while (IsListionContect)
            {
                //等待接受客户端连接,此处会“阻断”当前线程
                socMesgServer = socketServer.Accept();
                //获取远程节点信息
                string strClientIPAndPort = socketServer.RemoteEndPoint.ToString();
                //把远程节点信息添加到DropDown控件中
                Dropdown.OptionData op = new Dropdown.OptionData();
                op.text = strClientIPAndPort;
                Dro_IPList.options.Add(op);
                //把会话Socket添加到集合中(为后面发送信息使用)
                _DicSocket.Add(strClientIPAndPort, socMesgServer);
                //控件显示,有客户端连接
                
                //开启后台线程,接受客户端信息
                Thread thClientMsg = new Thread(ReceivMsg);
                thClientMsg.IsBackground = true;
                thClientMsg.Name = "thListionClientMsg";
                thClientMsg.Start(socMesgServer);
            }
        }
        catch (Exception)
        {
            
            throw;
        }
    }
    /// <summary>
    /// 后台线程,接受客户端信息
    /// </summary>
    /// <param name="sockMsg"></param>
    private void ReceivMsg(object sockMsg)
    { 
    
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

猜你喜欢

转载自www.cnblogs.com/Optimism/p/10535988.html
今日推荐