unity网络

Wesley13
• 阅读 481

网络

TCP:与打电话类似,通知服务到位

UDP:与发短信类似,消息发出即可

IP和端口号是网络两大重要成员

端口号(Port)分为知名端口号[0-1024,不开放)和动态端口号[1024,10000多,开放可用)

三次握手,四次挥手:

unity网络

unity网端简单案例:

**分为:**综合管理部分、客户端和服务器

需要Socket作为媒介来进行交互

见代码:

 一、综合管理部分:

 unity网络

unity网络

unity网络

unity网络 

unity网络unity网络

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using System.Net;
 5 using System.Net.Sockets;
 6 using System.Threading;
 7 using System;
 8 
 9 //综合管理部分
10 // 可以供客户端和服务器一块使用
11 public class TcpSocket
12 {
13     private Socket socket;//当前实例化的套接字
14     private byte[] data;//socket上的数据  
15     private bool isServer; //用来区分服务器  还是客户端
16 
17 //构造TcpSocket
18     public TcpSocket(Socket socket,int dataLength, bool isServer)
19     {
20         this.socket = socket;
21         data = new byte[dataLength];
22         this.isServer = isServer;
23     }  
24 // 接受----->客户端
25     public void ClientReceive()
26     {
27         //data:数据缓存   0:接受位的偏移量  length
28         socket.BeginReceive(data,0,data.Length,SocketFlags.None,new AsyncCallback(ClientEndReceive),null);
29     }
30     public void ClientEndReceive(IAsyncResult ar)
31     {
32         int receiveLength = socket.EndReceive(ar); //数据的处理      
33         string dataStr = System.Text.Encoding.UTF8.GetString(data,0, receiveLength); //把接受完毕的字节数组转化为 string类型
34         if (isServer)
35         {  Debug.Log("服务器接受到了:" + dataStr);           
36             for (int i = 0; i < Server.Instance.clients.Count; i++) //服务器要回什么
37             {
38                 if (Server.Instance.clients[i].ClientConnect())
39                 {
40                     Server.Instance.clients[i].ClientSeed(System.Text.Encoding.UTF8.GetBytes("服务器回复:"+ dataStr));
41                 }
42             }
43         }else {
44             DataManager.Instance.Msg = dataStr;            
45             Debug.Log("客户端接受到了:" + dataStr);
46         }
47     }
48 
49 
50 // 发送---->客户端发送给服务器
51     public void  ClientSeed(byte[] data)
52     {
53         socket.BeginSend(data,0, data.Length, SocketFlags.None,new AsyncCallback(ClientSeedEnd),null );
54     }
55 
56     private void ClientSeedEnd(IAsyncResult ar)
57     {
58         socket.EndSend(ar);
59     }
60 
61 
62 //连接----客户端与服务器连接
63     public void ClientConnect(string ip,int port)
64     {
65         socket.BeginConnect(new IPEndPoint(IPAddress.Parse(ip), port),new AsyncCallback(ClientEndConnect),null);
66     }
67     public void ClientEndConnect(IAsyncResult ar)
68     {
69         if (ar.IsCompleted) {
70             Debug.Log("连接成功");
71         }
72         socket.EndConnect(ar);
73     }
74 
75 // 客户端与服务器是否连接
76 
77     public bool IsClientConnect()
78     {
79         return socket.Connected;
80     }
81 //断开连接
82     public void ClientClose()
83     {
84         if (socket!=null&& ISClientConnect())
85         {
86             socket.Close();
87         }
88     }
89 
90 }

View Code

*二、服务器部分:*

unity网络

unity网络

      注意:回调函数AcceptClient只有当服务器接受连接(连接成功了)才会被调用.

unity网络 unity网络

 1 using System.Collections;
 2 using System.Collections.Generic;
 3 using UnityEngine;
 4 using System.Net;
 5 using System.Net.Sockets;
 6 using System.Threading;
 7 using System;
 8 
 9 // 服务器
10 
11 public class Server : MonoBehaviour {
12  
13     //单例服务器,继承Mono的
14     private static Server instance;
15     public static Server Instance
16     {
17         get {  return instance;  }
18     }
19     private void Awake()
20     {
21         instance = this;
22     }
23 //------------------------------------------------------------------------
24     private Socket server;//定义一个服务器
25     public List<TcpSocket> clients;//所有连接的客户端
26     private bool isLoopAccept = true;//是否循环接受客户端的请求
27     
28     void Start ()
29     {
30         //初始化服务器socket        协议族   
31         server = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);       
32         server.Bind(new IPEndPoint(IPAddress.Any,10086));//绑定端口号       
33         server.Listen(100); //可以监听的客户端数目
34 //------------------------------------------------------------------------    
35         //开辟一个线程      处理客户端连接请求  线程要暂停需用listenThread.Abort();
36         Thread listenThread = new Thread(ReceiveClient);
37         listenThread.Start(); //开启线程
38         listenThread.IsBackground = true; //后台运行
39 //------------------------------------------------------------------------
40         //初始化连接的客户端
41         clients = new List<TcpSocket>();
42  
43     }
44 
45 // 持续处理 接受客户端连接的请求  
46     private void ReceiveClient()
47     {
48         while (isLoopAccept)
49         {          
50             server.BeginAccept(AcceptClient,null); //开始接受客户端连接请求            
51             Debug.Log("检测客户端连接中.....");
52             Thread.Sleep(1000);//每隔1s检测 有没有连接我            
53         }       
54     }
55 // 客户端连接成功之后回调
56     private void AcceptClient(IAsyncResult ar)
57     {
58         //连接成功后处理该客户
59        Socket client = server.EndAccept(ar);
60        TcpSocket clientSocket = new TcpSocket(client,1024,true);
61        clients.Add(clientSocket); 
62        Debug.Log("连接成功");
63     }
64 //关闭项目终止线程,停止服务器.
65     private void OnApplicationQuit()
66     {
67         listenThread.Abort();
68         listenThread.IsBackground = true;//关闭线程
69     }
70 }

View Code

客户端部分:

unity网络

unity网络

unity网络 unity网络

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

//客户端
public class Client : MonoBehaviour {
    public InputField  input;
    public Text receiveText;

    TcpSocket tcpClient;
    Socket client;

    void Start () {
        //注册监听事件
        receiveText = GameObject.Find("ReceiveText").GetComponent<Text>();      
        
        tcpClient = new TcpSocket(client,1024,false);//初始化综合处理器
        client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//初始化客户端
    }              
    void Update () {
        if (tcpClient != null && tcpClient.IsClientConnect())//如果客户端不为空且客户端已连接
        {
            tcpClient.ClientReceive();//执行综合管理器中的ClientReceive()
        }
        receiveText.text = DataManager.Instance.Msg;
    }
    public void OnClickConnectBtn()//客户端向服务器开始连接输入(IP和端口号)按钮事件
    {
        if (!tcpClient.IsClientConnect())
        {
            tcpClient.ClientConnect("10.50.6.129",10086);
        }
    }
    public void OnClickToSendServer()//客户端向服务器发送文本消息按钮事件
    {
        if (tcpClient != null && tcpClient.IsClientConnect() && !String.IsNullOrEmpty(input.text))
        {
            tcpClient.ClientSeed(System.Text.Encoding.UTF8.GetBytes(input.text));
            input.text = "";
        }
    }
    private void OnApplicationQuit()//关闭项目,退出服务器连接
    {
        if (tcpClient != null && tcpClient.ClientConnect())
        {
            tcpClient.ClientClose();
        }
    }
    
}

View Code

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
2年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这