using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;namespace 服务器
{
    public partial class Form1 : Form
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        Socket clientsocket;
        string s_message;
        byte[] b_message;
        public Form1()
        {
            InitializeComponent();
        }        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            s_message = richTextBox1.Text;
            b_message = System.Text.Encoding.Default.GetBytes(s_message);
        }        private void Form1_Load(object sender, EventArgs e)
        {
        }        private void button2_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Any;
            IPEndPoint ipep = new IPEndPoint(ip, 2000);
            s.Bind(ipep);            s.Listen(10);
            s.BeginAccept(new AsyncCallback(callback1), null);
        }        public void callback1(IAsyncResult ar)
        {
            clientsocket = s.EndAccept(ar);
        }        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                 clientsocket.BeginSend(b_message, 0, b_message.Length, SocketFlags.None, new AsyncCallback(callback2), null);
            }
            catch (Exception wrong)
            {
                MessageBox.Show(string.Format("错误:" + wrong), "警告!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }        public void callback2(IAsyncResult ar)
        {
            clientsocket.EndSend(ar);
        }
    }
}调试 点击button1_Click那个按钮就出现异常  :System.NullReferenceException;未将对象引用设置到对象实例。帮帮忙,看看是哪里出现错误了。
还有就是想问一下  监听过后的那个while(true)循环应该写在哪?  

解决方案 »

  1.   

    先执行button2 click再点击button1,
      

  2.   

    clientsocket没有初始化当然要报错了
      

  3.   

    b_message 这个没有实例化第二个问题
     public void callback1(IAsyncResult ar) 
            { 
                clientsocket = s.EndAccept(ar); 
            } 
    在这里写下递归调用
     public void callback1(IAsyncResult ar) 
            { 
                clientsocket = s.EndAccept(ar); 
                
            } 
    s.BeginAccept(new AsyncCallback(callback1), null);
    不过这样写没什么意义,也只能管理一个客户端,若是想管理多个客户端,需要一个集合
      

  4.   

    1.  Socket clientsocket;  <== 未实例化
    2. 先执行button2 click再点击button1
    3. 代码很乱