日期:2014-05-17  浏览次数:20832 次

初学者求教Socket程序问题!!!
Socket的server端代码没有问题,问题出在client端。之前使用没有问题,程序是从网上下的,刚自己编了一个client来测多数据量传输会不会出现问题,结果出现一个小问题不能理解。

问题是这样的:如果client代码的最后两句clientsocket.Send(Encoding.Unicode.GetBytes(Convert.ToString(i++)));
  clientsocket.Receive(back);
  不加的话client程序会卡死,好像clientsocket.Receive(back)接不到数据,但发的数据发过去了。不理解的
  地方就在这,为什么只发一次接一次就有问题,如果在程序里再发一次接一次就没有问题了?望高手指点!


socket的server端代码:

static void Main() 
{
  IPAddress ip = IPAddress.Parse("127.0.0.1");//服务器IP地址
  //实例化套接字
  serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  //绑定套接字
  serverSocket.Bind(new IPEndPoint(ip, myport));
  //监听
  serverSocket.Listen(10);
  //Console.WriteLine("服务器已经启动");
  Thread th = new Thread(listenclient);

  th.Start();

  //result = Encoding.Unicode.GetBytes("00000");

Application.Run(new Form1());
   
}

  static void listenclient()//监听客户端
  {
  while (true)
  {

  Socket cliensocke = serverSocket.Accept();
  //Console.WriteLine("IP{0}已经连接", cliensocke.RemoteEndPoint);
  //cliensocke.Send(Encoding.Unicode.GetBytes("hello"));//为了确定连接
  Thread th = new Thread(receivemessage);
  th.Start(cliensocke);
  }
  }

  static void receivemessage(object cliensocke)
  {
  Socket myclient = (Socket)cliensocke;
  while (true)
  {
  try
  {
  //result = Encoding.Unicode.GetBytes("0");
  num = myclient.Receive(result);
  //Console.WriteLine("客户端发送的信息{0}", Encoding.Unicode.GetString(result, 0, num));
  str = Encoding.Unicode.GetString(result, 0, num);
   
  myclient.Send(Encoding.Unicode.GetBytes("ok"));
  //Thread.Sleep(2000);
  }
  catch
  {
  //int num = myclient.Receive(result);
  //Console.WriteLine("没有接收到信息");
  return;
  }
  }
  }


socket的client端代码:

namespace stability_test
{
  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();
  }

  private void timer1_Tick(object sender, EventArgs e)
  {
  byte[] back = new byte[1024];

  IPAddress ip = IPAddress.Parse("127.0.0.1");
  IPEndPoint iep = new IPEndPoint(ip, 8889);
  Socket clientsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  clientsocket.Connect(iep);

  listBox1.Items.Clear();
  //listBox1.Items.Add("9");
  //clientsocket.Send(Encoding.Unicode.GetBytes("9"));
  //clientso