unity socket通信简单案例

分享一个简单的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关闭;连接
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值