这里发送数据用的是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);
}
}
}
执行效果