---------------------------------我们开始先写我们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 Tcp客户端
{
class Program
{
static void Main(string[] args)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("10.80.11.60"),12345));
byte[] data = new byte[1024];
int count=clientSocket.Receive(data);
string msg = Encoding.UTF8.GetString(data, 0, count);
Console.Write(msg);
//while (true)
//{
// string s = Console.ReadLine();
// clientSocket.Send(Encoding.UTF8.GetBytes(s));
//}
for(int i = 0; i < 100; i++)
{
clientSocket.Send(Message.GetBytes(i.ToString()));
}
Console.ReadKey();
clientSocket.Close();
//先接收后发送
}
}
}
----------------------------------------------------------接下来我们服务器的代码----------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TcpSokectSever
{
class Message
{
private byte[] data = new byte[1024];
private int startIndex = 0;//存取多少个数据
public void AddCount(int count)
{
startIndex += count;
}
public byte[] Data
{
get
{
return data;
}
}
public int StartIndex
{
get
{
return startIndex;
}
}
public int RemainSize
{
get
{
return data.Length- startIndex;
}
}
//解析数据 读取数据
public void ReadMessage()
{
while (true)
{
if (startIndex <=4)
{
return;
}
int count = BitConverter.ToInt32(data, 0);
if ((startIndex - 4) >= count)
{
Console.WriteLine(startIndex);
string s = Encoding.UTF8.GetString(data, 4, count);
Console.WriteLine("解析出来一条数据:" + s);
Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
startIndex -= (count+4);
} else
{
break;
}
}
}
}
}
------------------------------------------------------接下来我们写Message来接收消息--------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TcpSokectSever
{
class Message
{
private byte[] data = new byte[1024];
private int startIndex = 0;//存取多少个数据
public void AddCount(int count)
{
startIndex += count;
}
public byte[] Data
{
get
{
return data;
}
}
public int StartIndex
{
get
{
return startIndex;
}
}
public int RemainSize
{
get
{
return data.Length- startIndex;
}
}
//解析数据 读取数据
public void ReadMessage()
{
while (true)
{
if (startIndex <=4)
{
return;
}
int count = BitConverter.ToInt32(data, 0);
if ((startIndex - 4) >= count)
{
Console.WriteLine(startIndex);
string s = Encoding.UTF8.GetString(data, 4, count);
Console.WriteLine("解析出来一条数据:" + s);
Array.Copy(data, count + 4, data, 0, startIndex - 4 - count);
startIndex -= (count+4);
} else
{
break;
}
}
}
}
}
----------------------------这样就可以解决-----------------------------