我们在tcp服务器中有100个设备正在侦听端口5224.我需要连接到这些设备并向每个设备发送一个字节数组并接收响应并显示这些数据。我尝试了异步套接字编程,但是当我添加了10多个设备时,它就停止了工作。是否有任何tcp套接字限制?我怎样才能解决这个问题(对不起我的英文)。 这是我的客户端套接字类:
public class ClientSocket
{
Socket so;
IPEndPoint serverEndpoint;
public byte[] SendBytes;
IPAddress ipaAddress;
int iPort;
public delegate void MessageReceivedEventHandler (object sender,byte[] bytes);
public event MessageReceivedEventHandler MessageReceived;
public ClientSocket(string ipAddress, string port)
{
try
{
ipaAddress = IPAddress.Parse(ipAddress);
iPort = int.Parse(port);
serverEndpoint = new IPEndPoint (ipaAddress , iPort);
so = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
so.ExclusiveAddressUse = true;
IAsyncResult rs = so.BeginConnect(serverEndpoint.Address, serverEndpoint.Port, new AsyncCallback(ConnectCallback), so);
rs.AsyncWaitHandle.WaitOne(100);
}
catch (Exception e)
{
}
}
private void ConnectCallback(IAsyncResult az)
{
try
{
Socket sk = (Socket)az.AsyncState;
sk.EndConnect(az);
socketObject soo=new socketObject();
soo.s = sk;
IAsyncResult rs = sk.BeginReceive(soo.b, 0, soo.b.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), soo);
rs.AsyncWaitHandle.WaitOne(1000);
}
catch (Exception ex)
{
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
socketObject oo = (socketObject)ar.AsyncState;
int received = oo.s.EndReceive(ar);
if (received > 0)
{
List<byte> ls = new List<byte>();
ls.AddRange(oo.b.ToList().GetRange(0, received));
oo.b = new byte[55];
oo.s.BeginReceive(oo.b, 0, oo.b.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), oo);
MessageReceived(so, ls.ToArray());
}
}
catch (Exception)
{
}
}
public void SendMessage (byte[] bytes)
{
try
{
IAsyncResult rs = so.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, new AsyncCallback(SendCallback), so);
rs.AsyncWaitHandle.WaitOne(1000);
}
catch (Exception)
{
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
so.EndSend(ar);
}
catch (Exception)
{
}
}
class socketObject
{
public Socket s;
public byte[] b=new byte[55];
}
public IPAddress SocketIPAddress
{
get{return ipaAddress;}
}
public int Port
{
get { return iPort; }
}
}