TCP同步连续传输大量数据出现数据不一致现象,求解决方法。
有两个类TCPService与TCPClient,这是我自己封装的两个Socket类,实现的原理是通过多线程实现同步数据通信
第一个类TCPService:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;
using PDSCommon;
using System.Threading;
namespace BottomCommunicate
{
public class TCPService
{
Socket soc;
const string State = "State";
const string Next = "Next";
const string End = "End";
const string Again = "Again";
IPEndPoint ips = null;
List<Socket> listSocket = new List<Socket>();
private TCPService() { }
public TCPService(string ip, int port)
{
//IPEndPoint ips = null;
try
{
ips = new IPEndPoint(IPAddress.Parse(ip), port);
}
catch
{
MessageBox.Show("IP或端口错误!");
}
soc = new Socket(ips.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
public TCPService(IPEndPoint ip)
{
ips = ip;
soc = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
}
#region ITcpService 成员
void Listen()
{
soc.Bind(ips);
soc.Listen(100);
ThreadPool.QueueUserWorkItem(ListenThread,soc);
}
void ListenThread(object obj)
{
Socket s = (Socket)obj;
Socket target = s.Accept();//当等待客户端连接时会阻塞
AcceptEvent(target);//与客户端建立连接,通知用户
listSocket.Add(target);
}
public bool Accept()
{
try
{
Listen();
return true;
}
catch (Exception ex)
{
MessageBox.Show("<TCPService,Accept>:" + ex.Message);
return false;
}
}
public event acceptSocket AcceptSocket;
void AcceptEvent(Socket target)
{
if (AcceptSocket != null)
AcceptSocket(target);
}
public bool Send(Socket target, byte[] data)
{
return Send(target, data, SocketFlags.None);
}
public bool Send(Socket target, byte[] data, SocketFlags socketflags)
{
lock (new object())
{
try
{
StateObject stateobject = new StateObject();
stateobject.target = target;
stateobject.data = data;
stateobject.socketflags = socketflags;
ThreadPool.QueueUserWorkItem(SendData, stateobject);
return true;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}