日期:2014-05-18  浏览次数:20724 次

winsocket的问题
在一个聊天程序里,我有两个方法“Connect to socket”和 ”AcceptCallback“, 我在“Connect to socket‘ 里用SocClient[nSoc].SendData(”a key“);去发送一串字符,请问我如何在”AcceptCallback“里接受这串字符。

public void AcceptCallback(IAsyncResult ar) 
{
try
{
allDone.Set();
WSocket listener = (WSocket) ar.AsyncState;
int nSoc = GetAvailbleSocket();
  SocClient[nSoc].Soc = (System.Net.Sockets.Socket)ListenSoc.Soc.EndAccept(ar);

SocClient[nSoc].SockRefNo = nSocRef;
SocClient[nSoc].RemoteUserName = txtIP.Text;
SocClient[nSoc].OnConnected += new ConnectDelegate(OnConnected);
SocClient[nSoc].OnDisconnected += new DisconnectDelegate(OnDisconnected);
SocClient[nSoc].OnReadyReceive += new ReceiveDelegate(OnReceive);
SocClient[nSoc].OnReadySend += new SendDelegate(OnReadySend);
SocClient[nSoc].OnConnectClose += new CloseDelegate(OnCloseRemote);
  //SocClient[nSoc].OnSockMessage += new MessageDelegate(OnSockMessage);

SocClient[nSoc].ReceiveData();  
ListViewItem item = new ListViewItem();
item.Text = nSoc.ToString();
item.SubItems.Add(SocClient[nSoc].Soc.RemoteEndPoint.ToString());
item.SubItems.Add(txtIP.Text);
 
listView1.Items.Add(item);

  //在这里如何能得到发送的字符串呢?

}
catch(Exception err) 
{

label1.Text ="Accept :"+ err.Message +err.Source.ToString();
}
}



private void button1_Click(object sender, System.EventArgs e)
{
  int nPort = Convert.ToInt32(txtCPort.Text);
IPEndPoint ipLocalEndPoint;
try
{
IPAddress ipAddress = Dns.GetHostAddresses(txtIP.Text.ToString())[0];
ipLocalEndPoint = new IPEndPoint(ipAddress, nPort);
}
catch(SocketException socErr )
{
MessageBox.Show(socErr.Message);
return;
}
  int nSoc = GetAvailbleSocket();
  try
{  

SocClient[nSoc].SockRefNo = nSoc;
if (SocClient[nSoc]==null)
InitSocket(ref SocClient[nSoc],nSoc);

if (!SocClient[nSoc].Soc.Connected)
SocClient[nSoc].AsyConnectTCIP(ipLocalEndPoint);
}
catch (Exception err) 
{
label1.Text="Connect Button :"+err.Message;
InitSocket(ref SocClient[nSoc],nSoc);
}

  //这样发送一个字符对吗?
  SocClient[nSoc].SendData("a key");
}

------解决方案--------------------
开一个线程,用while循环监听。
------解决方案--------------------
要循环监听。