深圳Unity3D培训
达内深圳龙华中心

185-8926-6248

热门课程

【深圳Unity3D培训】基于Socket通信的小实例

  • 时间:2017-09-18 10:16
  • 发布:深圳Unity3D培训
  • 来源:达内新闻

【深圳Unity3D培训】基于Socket通信的小实例

完成后果

先说全部实例在完成后果上,因为本实例只是对Socket相干的应用做了个根本的测试,所以在后果上确实是差强人意,也就不上图了,大要的后果描写便是:在Unity搭建的客户端,创立的UI按钮上停止点击,给办事端停止新闻的发送,尔后办事端前往响应的新闻,分歧的新闻发送有分歧的回应罢了。

后果不重要,究竟才根基,外面的道理才是咱们必要懂得的~
办事端搭建

这里的办事端,博主采用的是经由过程VS创立控制台法式,在电脑上开启办事端代码,主法式进口以下
Program.cs

 using System;    class Program

        {            static void Main(string[] args)            {

                Server server = new Server("127.0.0.1",8899);

                server.Start();
    
                Console.ReadKey();

            }

        }

实在主法式不过便是创立了办事类,开启办事罢了,而这里的办事类便是Socket相干应用的主体了
Server.cs

using System;    

using System.Collections.Generic;    

using System.Net;    

using System.Net.Sockets;    

class Server

{            

private Socket serverSocket;            

private Socket clientSocket;            

private IPAddress ipAddress;            

private IPEndPoint ipEndPoint;            

private List<Client> clientList = new List<Client>();    

public Server(string ip,int port)           

{                

//创立Socket
                

serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);                
//声名ip地点和端标语

this.ipAddress = IPAddress.Parse(ip);                

this.ipEndPoint = new IPEndPoint(ipAddress, port);

            }    
            
public void Start()            

{                

//Socket绑定IP和端标语
                

serverSocket.Bind(ipEndPoint);                //Socket开端监听
                
serverSocket.Listen(0);
    
Console.WriteLine("办事器曾经启动");    
    
//客户端接入
                
serverSocket.BeginAccept(AcceptCallback,null);
            
}    
            
private  void AcceptCallback(IAsyncResult ar)            {
                
clientSocket = serverSocket.EndAccept(ar);                //获得客户端称号
                
string clientName = clientSocket.RemoteEndPoint.ToString();
                
Client client = new Client(clientSocket, clientName);
                
client.Start();
                
Console.WriteLine(clientName + "曾经登录。。。");
    
clientList.Add(client);    
                
//继承轮回监听客户端的衔接
                
serverSocket.BeginAccept(AcceptCallback, null);
            
}
        
}

Server类的重要功效不过便是开启个Socket绑定确定的IP和端口,时候监听客户端的衔接。法式在这里采用的是异步方法,之所以代码上没有显著的线程挪用,是因为在采用了封装好的API,像 BeginXXX 如许的函数,为了能够轮回监听客户端的衔接也是在AcceptCallback外面继承开启客户端的监听,大要的逻辑是如许。

而这里的Client类可不是代表实际意义上的客户端,这里只是对客户端停止的相干治理,重要是对客户端的新闻发送和接管停止着处置,之所以采用两个类的方法,也是遭到面向工具思惟的影响,异样便于代码的治理。
Client.cs

 using System;    

using System.Text;    

using System.Net.Sockets;    

class Client

{           
 
private Socket clientSocket;            

private string clientName;            

private byte[] recieveData;    
            
public Client(Socket client,string clientName)            

{                

this.clientSocket = client;                

this.clientName = clientName;
                
recieveData = new byte[clientSocket.ReceiveBufferSize];
            
}    
            
public void Start()    
        
{
                
clientSocket.BeginReceive(recieveData,0,

clientSocket.ReceiveBufferSize,SocketFlags.None, RecieveCallback, null);
            
}    
            
//接管客户端的新闻
            
private void RecieveCallback(IAsyncResult ar)            

{               

try

{                    

//接管到的数据长度
                    
int count = clientSocket.EndReceive(ar);    
                    
//避免客户端非常加入
                    
if (count == 0)
                    
{
                        
clientSocket.Close();                        

return;
                    
}    
                    
//对接管到的数据停止处置
                    
string msgRec = Encoding.UTF8.GetString(recieveData, 0, count);
                    
HandleResponse(msgRec);    
                    
//输入到控制台
                    
Console.WriteLine(msgRec);    
                    
//轮回接管客户端发送过去的数据
                    
clientSocket.BeginReceive(recieveData, 0,

clientSocket.ReceiveBufferSize, SocketFlags.None, RecieveCallback, null);
                
}                

catch (Exception)
                
{                    

if (clientSocket != null)
                    
{
                        
clientSocket.Close();                        

return;
                    
}
                
}
                
}    
            
//对客户端前往过去的数据停止处置
            
private void HandleResponse(string data)            

{                

if (data.Equals("hello"))
                
{
                    
SendMessage("hello too");
                
}else if (data.Equals("haha"))                

{
                    
SendMessage("heihei");
                
}
            
}    
           
//发送新闻给客户端
            
private void SendMessage(string data)            

{                

byte[] msgData = Encoding.UTF8.GetBytes(data);
                
clientSocket.Send(msgData);
            
}
        
}

办事器端对客户端收回的哀求是在对新闻剖析后才处置的,也便是咱们的HandleResponse函数外面,这里只是简略的对客户端发送过去的字符串停止简略的if else断定罢了~

客户端创立

绝对办事器端的构建,客户端算是简略了很多,这里也就只有一个类来测试的。

Client.cs

using UnityEngine;   
 
using System.Text;    

using System.Net.Sockets;    

using System.Net;    

using System;    

using UnityEngine.UI;    

public class Client : MonoBehaviour {    
        
private Socket clientSocket;        

private byte[] recieveData;        

private Button btn1;        

private Button btn2;        

// Use this for initialization
        
void Start () {
    
InitNet();
    
btn1 = transform.Find("Btn1").GetComponent<Button>();
            
btn2 = transform.Find("Btn2").GetComponent<Button>();
    
btn1.onClick.AddListener(() => {
                
SendMsg("hello");
            
});
    
btn2.onClick.AddListener(() => {
               
SendMsg("haha");
            
});
        
}    

private void InitNet()        

{            

// 起首声名一个Socket
            
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            

//声名IP和端标语
            
IPAddress iPAddress = IPAddress.Parse("127.0.0.1");
            
IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, 8899);            //衔接办事器端
            
clientSocket.Connect(iPEndPoint);    
            
//接管办事端发送过去的新闻
            
recieveData = new byte[clientSocket.ReceiveBufferSize];
            
clientSocket.BeginReceive(recieveData, 0, clientSocket.ReceiveBufferSize, SocketFlags.None,
RevieveCallback, null);
        
}    
        
private void RevieveCallback(IAsyncResult ar)        

{            

int count = clientSocket.EndReceive(ar);            

string msgRec = Encoding.UTF8.GetString(recieveData, 0, clientSocket.ReceiveBufferSize);            

//输入信息
            
Debug.Log(msgRec);
            
recieveData = new byte[clientSocket.ReceiveBufferSize];
            
clientSocket.BeginReceive(recieveData, 0, clientSocket.ReceiveBufferSize, SocketFlags.None, RevieveCallback, null);
        
}    
        
private void SendMsg(string data)        

{           

 byte[] sendMsg = Encoding.UTF8.GetBytes(data);
            
clientSocket.Send(sendMsg);
        
}
   
}

在客户端初始Socket,确认IP和端标语就可以连上办事器了,尔后经由过程Unity的组件停止新闻的发送,尔后接管相干新闻,流程一步明了,的确不要太简略~

想知道更多关于IT行业的信息吗?想远远不如行动,行动起来,一起加入达内,一起进入IT行业,跟着达内的脚步,一起走进如今的互联网信息时代,带给你不一样的色彩生活——【深圳Unity3D培训

深圳达内

上一篇:【深圳Unity3D培训】unity中不可不知的13个小技巧
下一篇:【深圳Unity3D培训】了解AssetBundle

马上预约三天免费体验课

姓名:

电话:

增强现实技术(AR)及扩展应用

【深圳Unity3D培训】了解AssetBundle

【深圳Unity3D培训】基于Socket通信的小实例

【深圳Unity3D培训】为什么最近好多游戏公司都倒闭了?10个理由

选择城市和中心
贵州省

广西省

海南省