【第一章】初识Unity网络通信
服务端:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace NetStudyServer
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("这里是服务端");
//创建Socket
Socket listenfd = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//绑定IP和端口
IPAddress ipAddr = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEp = new IPEndPoint(ipAddr,8888);
listenfd.Bind(ipEp);
//开启监听
listenfd.Listen(0);
Console.WriteLine("服务端开启成功!");
while(true)
{
Socket connfd = listenfd.Accept();
Console.WriteLine("[服务器]Accept");
//接收数据
byte[] readBuff = new byte[1024];
int count=connfd.Receive(readBuff);
string readStr = System.Text.Encoding.Default.GetString(readBuff,0,count);
Console.WriteLine("[服务器接收到]"+ readStr);
//发送数据
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(readStr);
connfd.Send(sendBytes);
}
//Console.ReadKey();
}
}
}
客户端:
C#
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
public class Echo : MonoBehaviour {
Socket socket;
public InputField inputField;
public Text text;
void Start()
{
this.transform.Find("BtnConnect").GetComponent<Button>().onClick.AddListener(Connect);
this.transform.Find("BtnSend").GetComponent<Button>().onClick.AddListener(Send);
inputField = this.transform.Find("InputField").GetComponent<InputField>();
text = this.transform.Find("Text").GetComponent<Text>();
}
public void Connect()
{
//创建Socket
socket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//连接服务器【ip+端口】
socket.Connect("127.0.0.1",8888);
}
public void Send()
{
//获取文本内容
string sendStr = inputField.text;
//将字符串内容转换成字节数组
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
//像服务端发送消息
socket.Send(sendBytes);
//创建buffer字节通道
byte[] readBuff = new byte[1024];
//字节通道接收服务端返回的数据,返回字节数组长度
int count = socket.Receive(readBuff);
//根据字节通道里的数据和长度还原字符串
string recvStr = System.Text.Encoding.Default.GetString(readBuff,0,count);
text.text = recvStr;
//关闭socket连接
socket.Close();
}
}
评论