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

新人求助Socket..Accept()
我是跟着这位大哥写的socket
http://blog.csdn.net/tuwen/article/details/5365621

  public partial class Form1 : Form
  {
  public Form1()
  {
  InitializeComponent();

  }//end Form

  private void button1_Click(object sender, EventArgs e)
  {
  int serverMessageLength;//用于表示客户端发送信息的长度
  byte[] data = new byte[1024];//用于缓存客户端所发送的信息,通过socket传递的信息必须为字节数组
  IPAddress serverIP=IPAddress.Parse("192.168.0.203");
  IPEndPoint serverIPEndPoint = new IPEndPoint(serverIP, 9050);
  Socket newSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  newSock.Bind(serverIPEndPoint);//绑定
  newSock.Listen(10);//监听
  txtServerMessage.Text += "Waiting for a client";
  Socket client = newSock.Accept();//当有可用的客户端链接尝试时执行,并返回一个新的socket,用于与客户端之间的通信
  IPEndPoint clientIP = (IPEndPoint)client.RemoteEndPoint;
  txtServerMessage.Text += "\n Connect with client:" + clientIP.Address + " at port:" + clientIP.Port;
  data = Encoding.ASCII.GetBytes("Welcome here!");
  client.Send(data, data.Length, SocketFlags.None);//发送信息
  while (true)
  {
  data = new byte[1024];
  serverMessageLength = client.Receive(data);
  txtServerMessage.Text += " serverMessageLength" + serverMessageLength.ToString();
  if (serverMessageLength == 0)//当信息长度为0,说明客户端链接断开
  break;
  txtServerMessage.Text += Encoding.ASCII.GetString(data, 0, serverMessageLength);
  client.Send(data, serverMessageLength, SocketFlags.None);
  }
  txtServerMessage.Text += "Disconnected from " + clientIP.Address.ToString();
  client.Close();
  newSock.Close();
  }
  }//end Class

程序运行到红色的部分,就不再执行了,卡住了,为什么啊?我网上搜了其他的一些实力,也差不多这样,声明之后绑定IP地址,然后监听,然后就创建新的SOCKET,但是我这个却运行不了错在哪里啊?




newSock {System.Net.Sockets.Socket}
AddressFamily InterNetwork
Available 0
Blocking TRUE
Connected FALSE
DontFragment TRUE
EnableBroadcast “newSock.EnableBroadcast”引发了“System.Net.Sockets.SocketException”类型的异常
ExclusiveAddressUse FALSE
Handle 1036
IsBound TRUE
LingerState {System.Net.Sockets.LingerOption}
LocalEndPoint {192.168.0.203:9050}
MulticastLoopback “newSock.MulticastLoopback”引发了“System.Net.Sockets.SocketException”类型的异常
NoDelay FALSE
ProtocolType Tcp
ReceiveBufferSize 8192
ReceiveTimeout 0
RemoteEndPoint “newSock.RemoteEndPoint”引发了“System.Net.Sockets.SocketException”类型的异常
SendBufferSize 8192
SendTimeout 0
SocketType Stream
Ttl 64
UseOnlyOverlappedIO FALSE
静态成员
非公共成员


这个是红色那段程序对newSocket对象的监听。