Unity Socket TCP

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System;
using System.Threading;

namespace HelloSocket
{
    /// <summary>
    ///配置信息
    /// </summary>
    /// ip地址 端口 类型:TCP/UDP
    class HelloAddress
    {
        private static string host ="127.0.0.1";
        private static int port = 5055;
        private static IPAddress ip = IPAddress.Parse(host);
        public static IPEndPoint IPEP = new IPEndPoint(ip, port);
        public static Socket hSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        
        ///<summary>
        ///修改配置信息
        ///</summary>
        ///ip地址 端口 类型:TCP/UDP
        public static void SetHelloAddress(string ipStr, int iPort, System.Net.Sockets.ProtocolType type)
        {
            host = ipStr;
            port = iPort;
            ip = IPAddress.Parse(host);
            IPEP = new IPEndPoint(ip, port);
            hSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, type);
        }
    }

    ///<summary>
    ///客户端
    ///</summary>
    ///  API
    class HelloClient : HelloAddress
    {
        ///<summary>
        ///连接服务端
        ///</summary>
        public static void Main()
        {
            try
            {
                hSocket.Connect(IPEP);
                Thread threadConnect = new Thread(new ThreadStart(ReceiveMessage));
                threadConnect.Start();
            }
            catch (ArgumentNullException e)
            {
                Debug.Log(e.ToString());
            }
            catch (SocketException e)
            {
                Debug.Log(e.ToString());
            }
        }

        ///<summary>
        ///发送信息
        ///</summary>
        public static void SendMessage(string sendStr)
        {
            //确定是否连接
            if (hSocket.Connected)
            {
                IPEndPoint ipe = (IPEndPoint)hSocket.RemoteEndPoint;
                sendStr = ipe.ToString() + sendStr;
                byte[] bs = Encoding.ASCII.GetBytes(sendStr);
                hSocket.Send(bs, bs.Length, 0);
            }
        }

        ///<summary>
        ///接收信息
        ///</summary>
        private static void ReceiveMessage()
        {
            while (true)
            {
                byte[] recvBytes = new byte[1024];
                int iBytes = hSocket.Receive(recvBytes, recvBytes.Length, 0);
                if (iBytes <= 0)
                {
                    break;
                }
                string recvStr = "";
                recvStr+=Encoding.ASCII.GetString(recvBytes,0,iBytes);
                Debug.Log("服务端返回的数据:" + recvStr);
            }
        }
        ///<summary>
        ///关闭套接字
        ///<summary>
        public static void Close()
        {
            hSocket.Close();
        }
    }

    ///<summary>
    ///服务端
    ///</summary>
    /// API
    class HelloServer : HelloAddress
    {
        //存储连接服务端的所有用户
        public static List<Socket> listPlayer = new List<Socket>();
        private static Socket sTemp;
        ///<summary>
        ///服务端 绑定地址并监听
        ///</summary>
        public static void Main()
        {
            try
            {
                Thread threadListenAccept = new Thread(new ThreadStart(ListenAccept));
                threadListenAccept.Start();
            }
            catch (ArgumentNullException e)
            {
                Debug.Log(e.ToString());
            }
            catch (SocketException e)
            {
                Debug.Log(e.ToString());
            }
        }

        ///<summary>
        ///监听用户连接
        ///</summary>
        private static void ListenAccept()
        {
            hSocket.Bind(IPEP);
            hSocket.Listen(0);
            sTemp = hSocket.Accept();
            listPlayer.Add(sTemp);
            Thread threadReceiveMessage = new Thread(new ThreadStart(ReceiveMessage));
            threadReceiveMessage.Start();
            while (true)
            {
                sTemp = hSocket.Accept();
                listPlayer.Add(sTemp);
            }
        }
        ///<summary>
        ///接收信息
        ///<summary>
        private static void ReceiveMessage()
        {
            while (true)
            {
                byte[] recvBytes = new byte[1024];
                int iBytes =sTemp.Receive(recvBytes, recvBytes.Length, 0);
                if (iBytes <= 0)
                {
                    break;
                }
                string recvStr = "";
                recvStr += Encoding.ASCII.GetString(recvBytes, 0, iBytes);
                Debug.Log("客户端获取的数据:" + recvStr);
            }
        }
        ///<summary>
        ///发送信息
        ///</summary>
        public static void SendMessage(string sendStr)
        {
            IPEndPoint ipe = (IPEndPoint)sTemp.RemoteEndPoint;
            sendStr = ipe.ToString() + sendStr;
            byte[] bs = Encoding.ASCII.GetBytes(sendStr);
            sTemp.Send(bs, bs.Length, 0);
        }
        ///<summary>
        ///关闭套接字
        ///</summary>
        public static void Close()
        {
            for (int i = 0; i < listPlayer.Count; i++)
            {
                listPlayer[i].Close();
            }
            sTemp.Close();
            hSocket.Close();
        }
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神码编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值