分享一个简单的unity socket通信案例,欢迎学习
c#启动TCP服务端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
namespace ConsoleApp5
{
class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello word");
// 监听客户端
Socket Listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEp = new IPEndPoint(ipAdr, 8888);
Listenfd.Bind(ipEp);//套接字绑定Ip和端口
Listenfd.Listen(0);//开启监听,等待客户连接参数backog指定
//队列中等待的接受连接次数,0表示不限制
//IPAddress指定ip地址 IPEndPoint指定IP和端口
Console.WriteLine("[服务器]启动成功");
while (true)
{
Socket connfd = Listenfd.Accept();//接收客户端连接开始应答
Console.WriteLine("[服务器]Accept");
byte[] readBuff = new byte[1024];
int count = connfd.Receive(readBuff);//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);
}
}
}
}
unityTCP客户端
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Net.Sockets;
using UnityEngine.UI;
public class Echo : MonoBehaviour
{
private Socket socket;
public InputField inputFeid;
public Text test;
//点击连接按钮 SocketType传输类型 ProtocolType协议
public void Connection()
{
//AddressFamily地址族
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 8888);//开始播号 远程IP 远程端口
}
//点击发送
public void Send()
{
string sendStr = inputFeid.text;
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
socket.Send(sendBytes);//开始发送数据
byte[] readBuff = new byte[1024];
int count = socket.Receive(readBuff);//接收消息Receive,接收服务器数据
string recvStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);
//将数组转换成字符串显示在屏幕上
test.text = recvStr;
socket.Close();//通过Close关闭;连接
}
}