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

高分请教。有关C#中的sokcet编程问题
最近刚学C#,遇到有关socket的问题,有请高手帮帮忙。
目的是想实现一个client/server最简单的通信,采用socket编程。
问题主要出现在客户端代码,服务器断能够接收到客户端的数据,但是客户端的receive总是没有反应。
如果把 if (connSocket.Available == 0) 这个判断去掉而直接receive的话,客户端程序会死掉。
不知道问题在那儿,100分有请高手解答!分数不是问题!不够再加!电脑旁等候回复信息。

//server端主要代码如下:
//省略了部分无关紧要的代码。
namespace myServer
{
  public partial class frmMain : Form
  {
  private BackgroundWorker bwListener;
  private Socket listenerSocket;
  private IPAddress serverIP;
  private int serverPort;
  delegate void SetTextCallback(string text);
  private Socket socket;

  public frmMain()
  {
  InitializeComponent();

  bwListener = new BackgroundWorker();
  bwListener.WorkerSupportsCancellation = true;
  bwListener.DoWork += new DoWorkEventHandler(StartToListen);
  bwListener.RunWorkerAsync();
   
  txtServerIP.Text = "192.168.1.10";
  serverIP = IPAddress.Parse(txtServerIP.Text);
  serverPort = 8000;
   
  }

  private void StartToListen(object sender, DoWorkEventArgs e)
  {

  string sendToClient = "OK! You can exit now!!!";
  Byte[] bytesSentToClient = Encoding.ASCII.GetBytes(sendToClient);
  Byte[] bytesReceived = new Byte[256];

  this.listenerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  this.listenerSocket.Bind(new IPEndPoint(this.serverIP, this.serverPort));
  this.listenerSocket.Listen(200);

  int bytes = 0;
  string page = "Client's information: ";

  while (true)
  {
  try
  {
  socket = this.listenerSocket.Accept();
  SetText(((IPEndPoint)socket.RemoteEndPoint).Address.ToString());

  do
  {

  bytes = socket.Receive(bytesReceived, bytesReceived.Length, 0);
  int sendCount = 0;
  socket.SendTimeout = 1000;
  //在这里向客户端发送一句话,能够发送成功
  sendCount = socket.Send(bytesSentToClient);
  if (sendCount > 0)
  MessageBox.Show("send success");
  page = page + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
  }
  while (bytes > 0);
  }
  catch (SocketException se)
  {
  MessageBox.Show(se.Message + "\r\n错误代码: " + se.ErrorCode);
  return;
  }
  catch (Exception ee)
  {
  MessageBox.Show(ee.Message + "\r\n");
  return;
  }
   
  DisconnectServer();
  }
  }

  public void DisconnectServer()
  {
  this.bwListener.CancelAsync();
  this.bwListener.Dispose();
  this.listenerSo