C#簡單實現處理粘包

這裏發送數據用的是python 2.*,接收數據用C#,python是服務端,C#是客戶端
python服務端

# coding=utf-8
import socket
import struct
import sys
import time

if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf8')

HOST = "127.0.0.1"
PORT = 12345

myServer = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
myServer.bind((HOST, PORT))
myServer.listen(10)

client, addr = myServer.accept()
print client
start_time = time.time()
# 發送1000次
for i in range(0,1000):
    actionName = "你的父親是誰?"
    actionNameLength = len(actionName)

    data = "你的父親是我王半仙兒"
    dataLength = len(data)

    actionNameLengthBytes = struct.pack('i',actionNameLength)
    dataLengthBytes = struct.pack('i',dataLength)

    client.send(actionNameLengthBytes+actionName.encode("utf-8")+dataLengthBytes+data.encode("utf-8"))
    # 一秒60次左右
    time.sleep(0.017)
    print i
print time.time() - start_time

C#客戶端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace TCP客戶端
{
    class Program
    {
        static void Main(string[] args)
        {

            //創建socket
            Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //鏈接
            mySocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 12345));
            // 接收緩存
            byte[] resultBytes = new byte[1024];
            // 開始index
            int startIndex = 0;
			// 記錄接收到的次數
            int point = 0;
            while (true)
            {
            	// 接受一次數據
                int count = mySocket.Receive(resultBytes, startIndex, 1024 - startIndex, SocketFlags.None);
                // 如果沒有接收到數據,並且緩衝index到首位
                if (count == 0 && startIndex <= 0)
                {
                    break;
                }

                startIndex += count;
                // 接受一次,循環把數據取完,再娶下一次
                // 當然也可以不這樣
                while (startIndex > 0)
                {
                	//前面都要加上startIndex,
                	//很簡單因爲數據的爲止不都是從0開始的
                	//但我看網上的都是那樣寫的
                	//咱也不知道,咱也不敢說
                	//反正這樣應該是能簡單的實現以下
                    int actionLength = BitConverter.ToInt32(resultBytes, startIndex);
                    string actionName = Encoding.UTF8.GetString(resultBytes, startIndex + 4, actionLength);
                    Console.WriteLine(actionLength);
                    Console.WriteLine(actionName);

                    int dataLength = BitConverter.ToInt32(resultBytes, startIndex + 4 + actionLength);
                    string data = Encoding.UTF8.GetString(resultBytes, startIndex + 8 + actionLength, dataLength);
                    Console.WriteLine(dataLength);
                    Console.WriteLine(data);
                    Console.WriteLine("start index : " + startIndex);
                    point++;
                    Console.WriteLine("這是第:" + point);
                    Array.Copy(resultBytes, startIndex - count, resultBytes, startIndex, 1024 - startIndex);
                    startIndex -= count;
                }
            }
            Console.WriteLine("出來了");
            Thread.Sleep(100000);
        }
    }
}

執行效果
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章