在Unity内搭建一个简单的网络客户端
首先指定一下UI控件,用来输入和触发事件
ConnectToServer()方法用来连接服务器
SendAction()方法用来发送输入框的文档
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UnityEngine.UI;
public class ClientScripts : MonoBehaviour {
Socket clientSocket;
public InputField sendInput;
void Awake()
{
//开启后台运行(方便测试)
Application.runInBackground = true;
}
/*
*1.初始化套节字
*2.根据服务器IP和服务器端口,连接服务器
*3.发送数据
*4.接收数据
*
* */
public void ConnectToServer()
{
//1.初始化套节字
clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//2.连接服务器
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"),23456));
}
public void SendAction()
{
if(sendInput.text.length > 0)
{
//发送编辑框的内容
SendString(sendInput.text);
}
}
//3.发送数据
void SendString(string msg)
{
//1.将string转换成Byte数组
byte[] clientBuffer = UTF8Encoding.UTF8.GetBytes(msg);
//2.发送byte
clientSocket.BeginSend(clientBuffer,0,clientBuffer.Length,SocketFlags.None,SendFinish,clientSocket);
}
//发送完成回调方法
void SendFinish(System.IAsyncResult ar)
{
clientSocket = ar.AsyncState as Socket;
//发送了多少个字节
int count = clientSocket.EndSend(ar);
}
}
本文档介绍如何在Unity中创建一个基本的网络客户端。通过指定UI组件进行交互,实现ConnectToServer()方法连接服务器,并利用SendAction()方法发送用户输入的数据。
1401

被折叠的 条评论
为什么被折叠?



