C#中Socket与Unity相结合示例代码

2019-12-30 18:15:31刘景俊

最后是创建一个Unity的工程,搭建一个简单的页面,通过下面的代码你可以了解需要哪些组件


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

public class net : MonoBehaviour
{
 //ip和端口
 public InputField hostInput;
 public InputField portInput;

 //显示客户端接受的消息
 public Text recvText;
 public string recvStr;

 //显示客户端IP和端口
 public Text clientText;

 //聊天输入框
 public InputField TextInput;

 Socket socket;

 const int buffer_Size = 1024;
 public byte[] readBuff = new byte[buffer_Size];


 void FixedUpdate()
 {
  recvText.text = recvStr;
 }


 //连接服务器(需要一个Button触发)
 public void Connetion()
 {
  recvText.text = "";

  socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

  string host = hostInput.text;
  int port = int.Parse(portInput.text);

  socket.Connect(host, port);
  clientText.text = "客户端地址:"+socket.LocalEndPoint.ToString();
  socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb,socket);

 }

 /// <summary>
 /// 接受数据
 /// </summary>
 /// <param name="ar"></param>
 public void ReceiveCb(IAsyncResult ar)
 {
  
  try
  {
   int count = socket.EndReceive(ar);

   string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count);

   if (recvStr.Length > 300) recvStr = "";

   recvStr += socket.LocalEndPoint.ToString()+str + "n";
   Debug.Log("12346");
   socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb, socket);
  }catch(SocketException ex)
  {
   Debug.Log(ex);
  }
 }

 /// <summary>
 /// 发送数据,(需要一个Button触发)
 /// </summary>
 public void Send()
 {
  string str = TextInput.text;
  byte[] tex = System.Text.Encoding.UTF8.GetBytes(str);
  try
  {
   socket.Send(tex);
  
  }
  catch(SocketException ex)
  {
   Debug.Log(ex);
  }
 }
}

以上内容出自罗培羽老师《unity3d网络游戏实战》一书。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对ASPKU的支持。


注:相关教程知识阅读请移步到c#教程频道。