110,538
社区成员
发帖
与我相关
我的任务
分享
private void button1_Click(object sender, EventArgs e)
{
IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 9050);
m_mainsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_mainsocket.Bind(ipep);
m_mainsocket.Listen(10);
m_mainsocket.BeginAccept(new AsyncCallback(Accept), null);
}
void Accept(IAsyncResult iar)
{
try
{
m_memsocket[m_clientnum] = m_mainsocket.EndAccept(iar);
string str = "connected with" + m_clientnum.ToString() + "#";
//
label1.Invoke(new myeventhandler(SetLabelText), new object[] { str });
waitfordata(m_memsocket[m_clientnum]);
//
m_clientnum++;
m_mainsocket.BeginAccept(new AsyncCallback(Accept), null);
}
//
catch (ObjectDisposedException e)
{
}
}
public class socketpacket
{
public Socket m_currentsocket;
public byte[] data = new byte[1024];
}
void waitfordata(Socket s)
{
socketpacket theSockPkt = new socketpacket();
theSockPkt.m_currentsocket = s;
s.BeginReceive(theSockPkt.data, 0, theSockPkt.data.Length, SocketFlags.None, new AsyncCallback(ReceiveData), theSockPkt);
}
void ReceiveData(IAsyncResult iar)
{
socketpacket socketdata = (socketpacket)iar.AsyncState;
try
{
int recv = socketdata.m_currentsocket.EndReceive(iar);
//listBox1.Items.Add(Encoding.ASCII.GetString(socketdata.data,0,recv));
//data process
//...
//DataProc(socketdata);socketdata.data,socketdata.m_currentsocket;
//...
//listBox1.Invoke(new myeventhandler(AddListBoxItem), new object[] { Encoding.ASCII.GetString(socketdata.data, 0, recv) });
}
catch (SocketException e)
{
return;
}
waitfordata(socketdata.m_currentsocket);
}