Unity-网络编程 笔记1

本文详细介绍了如何在C#中通过TcpService.cs和Client.cs创建TCP服务端和客户端,包括服务端的监听、客户端的连接、消息的发送和接收。同时展示了如何在Unity中集成此功能进行数据交互。
摘要由CSDN通过智能技术生成

TCP相关API介绍与服务端编写

创建两个类TcpService.cs与Client.cs

TcpService.cs 用于启动TCP服务以及监听功能

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Service.Net
{
    internal class TCPService
    {
        TcpListener tcpListener;

        /// <summary>
        /// 启动服务端
        /// </summary>
        public void Start()
        {
            
            
        }
        /// <summary>
        /// 监听客户端的链接
        /// </summary>
        public async void Accpet()
        {
           
        }
    }
}

Client.cs 用于缓存客端端链接以及消息的接收与发送

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Service.Net
{
    internal class Client
    {
        TcpClient client;
        public Client(TcpClient tcpClient) 
        {
            client = tcpClient;
        }

        /// <summary>
        /// 接受消息
        /// </summary>
        public async void Receive()
        {
            
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        public async void Send(byte[] data)
        {
            
        }
    }
}

 实现TcpService.cs与Client.cs中的方法

 TcpService.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Service.Net
{
    internal class TCPService
    {
        TcpListener tcpListener;

        /// <summary>
        /// 启动服务端
        /// </summary>
        public void Start()
        {
            try
            {
                //创建监听器
                tcpListener = TcpListener.Create(7788);//端口范围1-65535
                tcpListener.Start(500);//允许接收多少客户端链接

                Console.WriteLine("Tcp Service Start!!!");

                Accpet();//开始监听
            }
            catch (Exception e) 
            {
                Console.WriteLine(e.ToString()); 
            }
            
        }
        /// <summary>
        /// 监听客户端的链接
        /// </summary>
        public async void Accpet()
        {
            try
            {
                TcpClient tcpClient = await tcpListener.AcceptTcpClientAsync();

                Console.WriteLine("客户端已连接:" + tcpClient.Client.RemoteEndPoint);//打印链接的客户端IP

                Client client = new Client(tcpClient);
                Accpet();
            }
            catch (Exception e)
            {
                tcpListener.Stop();//停止监听客户端链接
                Console.WriteLine($"Accpet:{e.Message}");
            }
            
        }
    }
}

 Client.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Service.Net
{
    internal class Client
    {
        TcpClient client;
        public Client(TcpClient tcpClient) 
        {
            client = tcpClient;
            Receive();
        }

        /// <summary>
        /// 接受消息
        /// </summary>
        public async void Receive()
        {
            try
            {
                while (client.Connected)
                {
                    byte[] buffer = new byte[4096];

                    int length = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
                    if (length > 0)
                    {
                        Console.Write($"接收到的数据长度:{length}--------");
                        Console.WriteLine($"接收到的数据长度:{Encoding.UTF8.GetString(buffer, 0, length)}");
                    }
                    else
                    {
                        //客户端关闭了
                        client.Close();
                        Console.WriteLine($"客户机{client.Client.RemoteEndPoint}断开连接");
                    }
                }
            }
            catch(Exception e)
            {
                Console.WriteLine($"Receive Error:{e.Message}");
                client.Close();
            }
               
        }
        
        /// <summary>
        /// 发送消息
        /// </summary>
        public async void Send(byte[] data)
        {
            try
            {
                await client.GetStream().WriteAsync(data, 0, data.Length);
                Console.WriteLine("数据发送成功");
            }
            catch(Exception e)
            {
                client.Close();
                Console.WriteLine($"Send Error:{e.Message}");
            }
            
        }
    }
}

编写启动脚本

using Service.Net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TCPService tcpService = new TCPService();
            tcpService.Start();
            Console.ReadLine();
        }
    }
}

实现客户端和服务器的消息收发

创建一个unity工程

新建脚本目录以及创建两个脚本

GameManager.cs与Clinet.cs

 Clinet.cs

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

public class Client
{
    static Client instance = new Client();
    public static Client Instance => instance;

    TcpClient client;
    //与服务端连接
    public void Start()
    {
        
    }

    //连接服务器
    public async void Connect()
    {
        
    }

    //接收数据
    public async void Receive()
    {
        
    }

    //发送数据
    public async void Send(byte[] data)
    {
        
    }
    
}

GameManager.cs

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

public class GameManager : MonoBehaviour
{
    void Start()
    {
        Client.Instance.Start();//开始连接服务器
    }

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))//按键发送数据给服务器
        {
            string str = "1234567890";//发送的数据内容
            byte[] data = Encoding.UTF8.GetBytes(str);//数据转换
            Client.Instance.Send(data);//发送数据
        }
    }
}

实现客户端Client方法

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

public class Client
{
    static Client instance = new Client();
    public static Client Instance => instance;

    TcpClient client;
    public void Start()
    {
        client = new TcpClient();
        Connect();
    }

    public void CloseConnect()
    {
        if(client.Connected)
            client.Close();
    }
    //连接服务器
    public async void Connect()
    {
        try
        {
            //通过使用IPAddress.Parse方法,可以将字符串表示的IP地址转换为IPAddress对象/
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            int port = 7788;
            await client.ConnectAsync( ip,port);
            Debug.Log("TCP 连接成功!!!");
            Receive();
        }
        catch(Exception e)
        {
            Debug.Log(e.Message);
        }
    }

    //接收数据
    public async void Receive()
    {
        try
        {
            while (client.Connected)
            {
                byte[] buffer = new byte[4096];
                int length = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
                if (length > 0)
                {
                    Debug.Log(Encoding.UTF8.GetString(buffer,0,length));
                    Debug.Log($"接收到的数据了长度为:{length}");
                }
                else
                {
                    client.Close();
                }
            }
        }
        catch (Exception e)
        {
            client.Close();
            Debug.Log(e.Message);
        }
    }

    //发送数据
    public async void Send(byte[] data)
    {
        try
        {
            await client.GetStream().WriteAsync(data,0,data.Length);
            Debug.Log("数据发送成功!!!");
        }
        catch (Exception e)
        {
            client.Close();
            Debug.Log(e.Message);
        }
    }
    
}

服务端数据发送

修改Receive()方法

接收到数据之后返回数据

Send(Encoding.UTF8.GetBytes("服务端数据:09876543210")); 

public async void Receive()
{
    try
    {
        while (client.Connected)
        {
            byte[] buffer = new byte[4096];

            int length = await client.GetStream().ReadAsync(buffer, 0, buffer.Length);
            if (length > 0)
            {
                Console.Write($"接收到的数据长度:{length}--------");
                Console.WriteLine($"接收到的数据长度:{Encoding.UTF8.GetString(buffer, 0, length)}");

                //收到数据之后,向客户端返回数据
                Send(Encoding.UTF8.GetBytes("服务端数据:09876543210"));
            }
            else
            {
                //客户端关闭了
                client.Close();
                Console.WriteLine($"客户机{client.Client.RemoteEndPoint}断开连接");
            }
        }
    }
    catch(Exception e)
    {
        Console.WriteLine($"Receive Error:{e.Message}");
        client.Close();
    }
       
}

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

shumake

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

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

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

打赏作者

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

抵扣说明:

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

余额充值