网络连接:拆包封包



using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using UnityEngine.UI;
using System.Text;
using System;
using System.Linq;
public class net : MonoBehaviour {
        int buffCount = 0;
        byte [] lenBytes = new byte [ sizeof ( UInt32 )]; //与Int都是4字节  带U的没有负数
        Int32 msgLength = 0;
        public InputField hostInput;
        public InputField portInput;
        //文本框
        public Text recvText;
        public string recvStr;
        public Text clientText;
        //聊天输入框
        public InputField textInput;
        //Socket和接收缓冲区
        Socket socket;
        public Button sengBtn;
        //接收缓冲区
        const int BUFFER_SIZE = 1024;
        public   byte [] readBuffer = new byte [BUFFER_SIZE];
        public Button chatBtn;
        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(readBuffer,0,BUFFER_SIZE, SocketFlags .None,ReceiveCb, null );
       }
        private void ReceiveCb( IAsyncResult ar)
       {
               try
              {
                      //count是接收数据的大小
                      int count = socket.EndReceive(ar);
                      //数据处理
                     buffCount += count;
                     ProcessData();
                     
                      //继续接收
                     socket.BeginReceive(readBuffer, 0, BUFFER_SIZE, SocketFlags .None, ReceiveCb, null );
              }
               catch ( Exception )
              {
                     recvText.text += "连接已断开" ;
                     socket.Close();
              }
       }
        private void ProcessData()
       {
               //小于长度字节   4
               if (buffCount < sizeof ( Int32 ))
                      return ;
               //消息长度
               Array .Copy(readBuffer, lenBytes, sizeof ( Int32 ));
              msgLength = BitConverter .ToInt32(lenBytes, 0);
               if (buffCount < msgLength + sizeof ( Int32 ))
                      return ;
               //处理消息
               string protocol = Encoding .UTF8.GetString(readBuffer, sizeof ( Int32 ), msgLength);
              HandleMsg(protocol);
               //清除已处理的消息
               int count = buffCount - msgLength - sizeof ( Int32 );
               Array .Copy(readBuffer, msgLength, readBuffer, 0, count);
              buffCount = count;
               if (buffCount > 0)
              {
                     ProcessData();
              }
       }
        private void HandleMsg( string protoBase)
       {
               string proto =protoBase;
               Debug .Log( "接收 " + proto);
       }
        //发送数据
        public void Send()
       {
       
               string str= textInput.text;
               byte [] bytes = Encoding .UTF8.GetBytes(str);
               byte [] length = BitConverter .GetBytes(bytes.Length);
               byte [] sendbuff = length.Concat(bytes).ToArray();
              socket.Send(sendbuff);
       }
        // Use this for initialization
        void Start () {
              sengBtn.onClick.AddListener(sengBtnCallBack);
              chatBtn.onClick.AddListener(chatBtnCallBack);
       }
        private void chatBtnCallBack()
       {
              Send();
       }
        private void sengBtnCallBack()
       {
              hostInput.text= "127.0.0.1" ;
              portInput.text = "9568" ;
              Connetion();
              
       }
        //因为只有主线程能够改UI组件的属性、
        //因此在Upadate里更换脚步
        void Update () {
              recvText.text = recvStr;
       }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值